restricting vector size input

4 ビュー (過去 30 日間)
Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves 2020 年 1 月 11 日
コメント済み: Adam Danz 2020 年 1 月 12 日
I need the user to enter a vector with the dimension given by himself in a previus input which is componente variable.
Here's my code:
dist = zeros(1, componente); % Preallocate space.
definput = {'0'};
prompt={'Insira as distâncias de cada trecho com um espaço entre elas'};
titleBar= 'Distâncias dos trechos';
dims=[1 50];
dado='';
while isempty(dado) | length(dado) ~= componente
% Ask user for a number.
dado = inputdlg(prompt, titleBar, 1, definput);
if isempty(answer),break,end % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue = str2double(answer{1});
% Check usersValue1 for validity.
end
dist = dado;

採用された回答

Adam Danz
Adam Danz 2020 年 1 月 11 日
編集済み: Adam Danz 2020 年 1 月 12 日
See the inline comments for the 3 changes I made to your code.
I'm assuming that the user is providing a vector of numbers as input and that you are requiring the vector to be of size 'dims'. This uses validateattributes(A,classes,attributes) which will throw a well written error message if the assumptions are not met.
while isempty(dado) || length(dado) ~= componente
% Ask user for a number.
% CHANGE 1: Assuming 'dado' output should be 'answer' based on lines below
% dado = inputdlg(prompt, titleBar, 1, definput);
answer = inputdlg(prompt, titleBar, 1, definput);
if isempty(answer),break,end % Bail out if they clicked Cancel.
% Convert to floating point from string.
% CHANGE 2: Assuming answer is a vector in which chase this line below
% will not work; replaced with sscanf line.
%usersValue = str2double(answer{1});
userValue = sscanf(answer{1},'%g').';
% CHANGE 3: Check that userValue is a double array of size dims.
% Check usersValue1 for validity.
validateattributes(userValue,{'double'},{'size',dims})
end
Note that since the user is entering a vector, it may be better to test that the input vector has an expected number of elements rather than having an expected size. That would look like this (where 'n' is the expected number of elements).
validateattributes(userValue,{'double'},{'numel',n})
  2 件のコメント
Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves 2020 年 1 月 12 日
Didnt know this function.. Will help me tons.. Thanks Adam!
Adam Danz
Adam Danz 2020 年 1 月 12 日
Glad I could help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by