Saving data from loops

Sir I have the following code. I have to store all the value of choice for (1 to n) iterations. How can I do it?
for index = 1 : length(accumulation)
if (accumulation(index) > p)
chosen_index = index;
break;
end
end
choice = chosen_index;

回答 (2 件)

madhan ravi
madhan ravi 2019 年 7 月 6 日
編集済み: madhan ravi 2019 年 7 月 6 日

0 投票

What values are you going to store? The chosen_index is for sure a scalar because as soon as the condition is satisfied once the loop stops executing, your code is achieved using one line:
The_chosen_one = find(accumulation > p,1,'first')
If your question is how to store values in a loop then:
% an example
x = randi(10,1,10);
y = zeros(size(x)); % preallocate
for k = 1:numel(x)
y(k) = x(k) * 2;
end
Tatvam Dadheech
Tatvam Dadheech 2019 年 7 月 6 日

0 投票

There are two ways to do it.
x = [];
for i = 1:n
x = [x; choice(i)]
end
Above code will append the value of choice at ith index to the x.
x = zeros(n,1);
for i = 1:n
x(i) = choice(i);
end
You can also preallocate and assign the value to ith index of x.

カテゴリ

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

タグ

質問済み:

2019 年 7 月 6 日

回答済み:

2019 年 7 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by