restricting vector size input

조회 수: 2 (최근 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 CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by