restricting vector size input

2 次查看(过去 30 天)
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
Didnt know this function.. Will help me tons.. Thanks Adam!

请先登录,再进行评论。

更多回答(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