How can I apply the loop method for this program ?

I want create a program that continuously asks the user to enter numbers until the user enters a negative number. The numbers before the last one (non-negative numbers) are saved in a vector B. Then I want to display B and the average value in B. For instance, if the user enters 3, 5, 0, 7, 11, -3, the input stops and B is [3, 5, 0, 7, 11]. The average value of B is 5.2.
I know how to do it with the built-in functions of Matlab, but can not figure out how to do it with the loop method. Help !
Thanks,

 採用された回答

Image Analyst
Image Analyst 2014 年 2 月 17 日

0 投票

Try this:
count = 0;
defaultValue = 45;
titleBar = 'Enter a number';
userPrompt = 'Enter the number';
while count < 100 % failsafe - max amount we ever expect so don't get infinite loop
% Ask user for a number.
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),break,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
theNumber = str2double(cell2mat(caUserInput));
% Check for a valid integer.
if isnan(theNumber)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
theNumber = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', theNumber);
uiwait(warndlg(message));
end
% Exit if number is negative:
if theNumber < 0
break;
end
count = count + 1;
B(count) = theNumber;
end
if count >= 1
% Display B
B
% Display mean of B
meanB = mean(B);
fprintf('The mean of B = %.3f\n', meanB);
end

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2014 年 2 月 17 日

回答済み:

2014 年 2 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by