How to make variables in a while loop be an array

2 次查看(过去 30 天)
Could anybody help me with this please? I am trying to work out a optimisation problem. I am using a while loop. I am able to obtain results in an array e.g. result(n).however, I am not able to make variable "n" as an array,hence, the value that I can access is always the last n value appeared. I would like to know how to make the variables into an array form that I can access the optimal result,aslo the corresponding variable "n" value.
  3 个评论
zhe li
zhe li 2011-11-2
Thank you very much for your response Mr Jiang. However, I may have not explained my problem properly. As the "n" shown should be the variables,hence please have a look the loop written and hoping make it more clear,
idx = 0;
while ....
result(n) = ....
n = n + 1; %!
all_n(idx) = n; %! ???????????????
end
Which as the "result" will be in an array, I can use "max" function to obtain the optimal result,however, I can not obtain a corresponding "n" value,for instance, if the results look at [result(n)]= 1 4 6 8 3, and n is always showning as n=1, n= 2,n=3,n=4,n=5. however,the optimal result appeared as the fourth term,which the corresponding n value should be n=4. I hope I have explained my problem clearly. please help me with this problem. Many thanks.
zhe li
zhe li 2011-11-2
Sorry, the initial value should be n=0 before the while loop.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2011-11-2
idx = 0;
while ....
n = ....
result(n) = ....
idx = idx + 1; %!
all_n(idx) = n; %!
end
Then later you can (for example)
for K = 1 : idx
this_n = all_n(idx);
disp(result(this_n))
end
  4 个评论
Walter Roberson
Walter Roberson 2011-11-2
[maxvalue, maxidx] = max(result);
Then the index of the maximum value is maxidx
This does not require that the n be recorded.
zhe li
zhe li 2011-11-2
Thanks a million Mr Roberson. I think I got the answer. I really appreciate your help.

请先登录,再进行评论。

更多回答(0 个)

类别

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