Expanding 1D array using for loop

3 ビュー (過去 30 日間)
Maroulator
Maroulator 2014 年 9 月 7 日
回答済み: Star Strider 2014 年 9 月 7 日
I have the code below. What I am trying to do is accept/store an arbitrary number of positive input values (into the "values" array) using a for loop. I do not have a pre-determined amount of positive numbers, that I am going to accept, rather the goal is for the user to keep entering numbers (as prompted) until he/she enters a non-positive number. I think the crux of the problem lies with dynamically expanding the values array.
Any suggestions?
i=1;
n=input('Enter initial value: ');
values(i)=n;
for i=1:length(values)
if n>0;
n=input('Enter next value: ');
i=i+1;
else
disp('ERROR: All numbers entered must be positive!');
break;
end
end

採用された回答

Star Strider
Star Strider 2014 年 9 月 7 日
This seems to work:
n = 1;
i = 0;
n=inputdlg('Enter initial value: ');
n = str2num(cell2mat(n));
while n>0;
i=i+1;
values(i) = n;
n=inputdlg('Enter next value: ');
n = str2num(cell2mat(n));
end
msgbox('ERROR: All numbers entered must be positive!');
I used the inputdlg and msgbox functions because they keep the Command Window from getting cluttered.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by