How can I gather all the values from a loop into an array?

1 回表示 (過去 30 日間)
Raquel Terrer van Gool
Raquel Terrer van Gool 2020 年 5 月 5 日
コメント済み: Star Strider 2020 年 5 月 5 日
Hi,
I was wondering how can I gather all the values into an array because I need to plot the answer later. This is part of the code I am writing:
for i=x0:h1:xx-h1 % Where h1 is the step size
y1=y1+dy(i,y1)*h1;
i=i+h1;
end
If someone knows, please let me know! Thanks!
  3 件のコメント
Raquel Terrer van Gool
Raquel Terrer van Gool 2020 年 5 月 5 日
This is the full code. When I try to do that, I get an error saying that the array indices must be positive and logical.
yi=@(x)exp(1/3*x.^3-1.2*x);
dy=@(x,y)y*x.^2-1.2*y;
x0=0; xx=2; y1=1; y2=1;
xp=[0:0.01:2];
h1=0.25;
h2=0.1;
for i=x0:h1:xx-h1 % Where h1 is the step size
y1=y1+dy(i,y1)*h1;
i=i+h1;
end
for i=x0:h2:xx-h2 % Where h2 is the step size
y2=y2+dy(i,y2)*h2;
i=i+h2;
end
Raquel Terrer van Gool
Raquel Terrer van Gool 2020 年 5 月 5 日
Thank you very much for your help!

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

採用された回答

Star Strider
Star Strider 2020 年 5 月 5 日
編集済み: Star Strider 2020 年 5 月 5 日
Knowing only what you posted, I would do something like this:
i=x0:h1:xx-h1; % Where h1 is the step size
y1v = zeros(size(i)); % Preallocate
for k = 1:numel(i)
y1=y1+dy(i,y1(k))*h1;
y1v(k) = y1;
end
That stores the existing values of ‘y1’ as vector ‘y1v’ so it stores the values while not otherwise disrupting the code. The ‘i’ vector is now separate, so to plot them later, something like this would likely work:
figure
plot(i, y1v)
grid
I did not test this, however it should work.
EDIT —
With the full code (not available when I first posted this), it changes to:
yi=@(x)exp(1/3*x.^3-1.2*x);
dy=@(x,y)y*x.^2-1.2*y;
x0=0; xx=2; y1=1; y2=1;
xp=[0:0.01:2];
h1=0.25;
h2=0.1;
i1=x0:h1:xx-h1; % Where h1 is the step size
y1v = zeros(size(i1)); % Preallocate
for k = 1:numel(i1)
y1=y1+dy(i1(k),y1)*h1;
y1v(k) = y1;
end
i2=x0:h2:xx-h2; % Where h2 is the step size
y2v = zeros(size(i2)); % Preallocate
for k = 1:numel(i1)
y2=y2+dy(i2(k),y2)*h2;
y2v(k) = y2;
end
figure
plot(i1, y1v, i2, y2v)
grid
This runs without error, and appears to produce the correct result.
  4 件のコメント
Raquel Terrer van Gool
Raquel Terrer van Gool 2020 年 5 月 5 日
The edit ran with no problem!
Star Strider
Star Strider 2020 年 5 月 5 日
Great!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by