How to save each value from an iterative solution

Hello,
I am using an iterative solver and would like to be able to save each solution so that they can be plotted.
For the simplified example below:
y=4;%initial value of y
x=[1:5];
for i=1:5;
y=y+x(i);
end
I would like to have each value for y saved as a separate variable in the workspace so that these can be plotted. Something like:
y1 = 5;
y2 = 7;
y3 = 10;
y4 = 14;
y5 = 19;
Y=[y1,y2,y3,y4,y5];
plot(x,Y);
Alternatively if these values for y can be concatenated directly it would be just as useful.
Many thanks
Gareth

 采纳的回答

y(1)=4;
x=[1:5];
for i=1:5
y(i+1)=y(i)+x(i);
end
y=y(2:6);
plot(x,y)
Best wishes
Torsten.

3 个评论

Thanks,
This allows me to solve the equation while storing the original y value.
This answer includes several code errors that beginners often make, and that are highlighted by the MATLAB editor:
  • it expands y on every iteration: arrays should be preallocated before any loop.
  • the index name i should not be used, as this is the name of the inbuilt imaginary unit.
I wouldn't call it "errors", I'd call it "MATLAB-tolerated deficiencies" :-)
Best wishes
Torsten.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by