my inputs length arent matching

1 次查看(过去 30 天)
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

采纳的回答

Image Analyst
Image Analyst 2019-12-29
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

更多回答(1 个)

Daniel Ribeiro Gonçalves
Works perfectly!
Thnxs!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by