my inputs length arent matching

1 Ansicht (letzte 30 Tage)
Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves am 29 Dez. 2019
Hi people,
My program asks for the number of loads (cargas), and then asks for the values of each load(potencia).
My program should only be run if my potencia variable length matches the cargas variable length.
When I run it my potencia length is giving me a bigger number then the number of inputs I enter in command window.
I think that's because of the s specification, but I'm not finding another way to solve it. Could you help me?
carga = input('Insira o número total de cargas:');
cargas= 1:carga;
%Meu input de potência deve pedir a quantidade de cargas
potencia=input('Insira as potências das cargas:', 's');
potencia = [potencia];
% A quantidade de potências deve ser igual a quantidade de cargas
if length(potencia) > length(cargas) | length(potencia) < length(cargas)
fprintf('A quantidade de potências deve ser igual a quantidade de cargas');
end

Akzeptierte Antwort

Image Analyst
Image Analyst am 29 Dez. 2019
Try this:
carga = input('Insira o número total de cargas : ');
cargas= 1:carga;
potencia = zeros(1, carga); % Preallocate space.
defaultValue = {'0'};
titleBar = 'Enter a number';
for k = 1 : carga
%Meu input de potência deve pedir a quantidade de cargas
userPrompt = {sprintf('Enter value #%d : ', k)};
% Keep asking user for something until they enter a number.
caUserInput = '';
while isempty(caUserInput)
% Ask user for a number.
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),break,end % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue = str2double(caUserInput{1})
% Check usersValue1 for validity.
if isnan(usersValue)
% If it's a NAN, they didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.', usersValue);
uiwait(warndlg(message));
caUserInput = '';
end
end
% Value is good (a number) if we get here.
potencia(k) = usersValue;
end

Weitere Antworten (1)

Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves am 29 Dez. 2019
Works perfectly!
Thnxs!

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by