restricting vector size input

4 vues (au cours des 30 derniers jours)
Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves le 11 Jan 2020
Commenté : Adam Danz le 12 Jan 2020
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;

Réponse acceptée

Adam Danz
Adam Danz le 11 Jan 2020
Modifié(e) : Adam Danz le 12 Jan 2020
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 commentaires
Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves le 12 Jan 2020
Didnt know this function.. Will help me tons.. Thanks Adam!
Adam Danz
Adam Danz le 12 Jan 2020
Glad I could help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by