my inputs length arent matching

조회 수: 2 (최근 30일)
Daniel Ribeiro Gonçalves
Daniel Ribeiro Gonçalves 2019년 12월 29일
답변: Daniel Ribeiro Gonçalves 2019년 12월 29일
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
Daniel Ribeiro Gonçalves 2019년 12월 29일
Works perfectly!
Thnxs!

카테고리

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