I have a for loop, but every iteration overwrites the variable and I have only the final data left.. how can I save data from every loop
for mp=1:100
zsx=somecalc(mp)
end
saves only the last value when mp=100. how do I get the other values?

 採用された回答

Thomas
Thomas 2012 年 3 月 28 日

4 投票

Thomas Anthony answered on 8 Mar 2012 at 15:06
This video should help:
You can save the output in a vector or matrix as shown,
Eg:
for i=1:10
y(i)=i+rand; % use y(i) so that it is written as a vector
end
or you could use:
z=[];
for i=1:10
z=[z i+rand];
end
both should give you similar results..

4 件のコメント

Rahul
Rahul 2012 年 3 月 28 日
thanks, works! did not expect an answer so soon
Matt Tearle
Matt Tearle 2012 年 3 月 28 日
Don't forget to preallocate space for the output
% Preallocate space for zsx
zsx = zeros(1,100);
% Loop through elements
for mp = 1:100
% Save mpth element
zsx(mp) = somecalc(mp);
end
Avoid z = [z new_element] in a for loop.
Austin Hernandez
Austin Hernandez 2020 年 4 月 27 日
I have a similar issue but I need to record the y-values of a line from x=a to x=b.
Each loop, the slope of the line will change so there will be a different set of x and y's for each loop
How can I record the y-values from the function for each loop? The above fix doesn't work if a function is inside of it. This is my code and gives me an error once it trys to record y(i):
function for_test
y = ones(1,1);
for i=1:10
x = 0:1:10;
y(i) = x+rand; % use y(i) so that it is written as a vector
end
%I want to be able to access both sets of information when the for loop is over.
end
Mahsa Amiri
Mahsa Amiri 2020 年 7 月 16 日
Tahnk you Thomas!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

製品

タグ

質問済み:

2012 年 3 月 28 日

コメント済み:

2020 年 7 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by