Taking a value from a previous for loop

I have created a function to compute the Euler of a given IVP as seen below:
function U= Uler(N,h,y)
t = 0;
S = N/h;
for i=1:S
y = y +(h*(0.5*y*(1-y/2)))
t = t +h
end
U=y
end
I was wondering how do I take one of the values of past values of Y to calculate something later. For example if I do Uler(0.2,0.1,0.1) That would do the for loop twice giving me a value for y2, now how I would I go about finding y1 to implement later?

回答 (2 件)

Birdman
Birdman 2017 年 11 月 13 日

1 投票

You have to use indexing for it, define y and t as vectors. By this, you can reach any previous value that you want.
function U= Uler(N,h,y)
t = 0;
S = N/h;
y(1)=0;
t(1)=0;
for i=1:S
y(i) = y(i) +(h*(0.5*y(i)*(1-y(i)/2)))
t(i) = t(i) +h
end
U=y
end
Jan
Jan 2017 年 11 月 13 日
編集済み: Jan 2017 年 11 月 13 日

0 投票

Store all intermediate results in a pre-allocated vector
function [y, t] = Uler(N,h,y0)
t = 0;
S = floor(N/h);
y = zeros(1, S); % Pre-allocate
y(1) = y0; % Copy initial value
t = zeros(1, S);
for i = 2:S
y(i) = y(i-1) + (h*(0.5*y(i-1)*(1-y(i-1)/2)));
t(i) = t(i-1) + h;
end
end

1 件のコメント

James Pain
James Pain 2017 年 11 月 13 日
Cheers, this is a really helpful. Although how would I take a value from the pre-allocated vector to use in the function later?

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

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

製品

質問済み:

2017 年 11 月 13 日

コメント済み:

2017 年 11 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by