euler function that you can reuse with different values?

function [t, y, yprime]=euler(f,t0,tN,y0,N)
h=(tN-t0)/N;
t=t0:N:tN;
y=zeros(1,N+1);
yprime=f(t,y);
y(1)=y0;
t(1)=t0;
for i=1:N
t=(i-1)*h;
y(i)=y(i)+h*(f(y(i),t(i)));
end
end
this is my code for a euler method function. I cant seem to get it to run properly. Any ideas on what i am doing wrong. please help!
[SL: formatted function as code]

3 件のコメント

Benjamin Trivers
Benjamin Trivers 2020 年 2 月 18 日
f=@(t,y) (1/t.^2)-(y./t)-(y.^2);
t0=1;
tN=2;
y0=1;
N=10;
[t, y, yprime]=euler(f,t0,tN,y0,N);
this is my script that I am trying to get it to read the euler.m file
Jacob Wood
Jacob Wood 2020 年 2 月 18 日
It looks like you define f(t,y), but then when it is called inside the euler function it is called as f(y,t). Could that be a problem?
Benjamin Trivers
Benjamin Trivers 2020 年 2 月 18 日
whenever, i take that part out the part in the yprime gets a red line under it and doesnt like it.

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

回答 (1 件)

Srivardhan Gadila
Srivardhan Gadila 2020 年 2 月 25 日

0 投票

In your function euler, check for the following:
  1. In line 3 it should be "t=t0:h:tN;"
  2. In line 9 why are you changing the vector t to "(i-1)*h" ?
  3. In line 10 it should be "f(t(i), y(i))"
And for the function f:
f=@(t,y) (1/t.^2)-(y./t)-(y.^2);
Replace the (1/t.^2) with (1./t.^2) i.e., it should be:
f=@(t,y) (1./t.^2)-(y./t)-(y.^2);

カテゴリ

タグ

質問済み:

2020 年 2 月 18 日

回答済み:

2020 年 2 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by