saving data during iterations

2 views (last 30 days)
I am working on some iterative calculations and I need to be able to save the results of the iteration at various times during the calculation.
I know that I can plot the results of each step with "hold on" and the plot command. What I cannot figure out is how to write the results of each iteration either to the workspace as a new variable or to a file so that I can load it into something else later,
Here is what I have so far
x = [1 2 3 4 5]
y= [1.5, 2.5, 3.5, 4.5, 5.5]
for k=1:10
buff1 = y
for x=1:5
y(x)=buff1(i)+y(i)
end
hold on
plot(x, y)
end
What I want to do is to have a listing of y for each of the 10 iterations.
Thanks
Cliff

Accepted Answer

Jesus Sanchez
Jesus Sanchez on 24 Feb 2020
Edited: Jesus Sanchez on 24 Feb 2020
It seems that you are overwriting y in each iteration. Being that the case, I would create a matrix stored_y to save the values of that variable. Something like this. I tested it by setting i = 1.
x = [1 2 3 4 5]
y= [1.5, 2.5, 3.5, 4.5, 5.5]
stored_y = zeros(11,5); % Data for each iteration is stored on rows.
stored_y(1,:) = y; % Saves "first" value of y.
for k=1:10
buff1 = y;
for x=1:5
y(x)=buff1(i)+y(i);
end
stored_y(1+k,:) = y; % Saves calculated value of y
% hold on
% plot(x, y)
end
Now, in order to plot stored_y you could do something like this:
figure
hold on
x=1:5;
for n=1:size(stored_y,1)
plot(x,stored_y(n,:));
end
  2 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!