I am trying to make use of my own Euler function to solve small ODE systems with regular Euler method in Octave. I made it work for 1x1 matrix input, but I want to use it for 2x2 matrix input as well.
My code looks like this:
%Euler method for an ODE system of 2x2 matrix input (equation 1) and 1x1 input (equation 2)
function [t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)
h=(tf-t0)/n; %Constant step size
t=t0:h:tf;
x=[x0 x0] ; y=[y0]; %Starting values
for j=1:n
keulerf1=f1(t(j),x,y); %f1=dx/dt (from first equation) % I think the problem with dimensions might be here****
keulerf2=f2(t(j),x,y); %f2=dy/dt (from second equation)
x=x+h*keulerf1; %Euler forward method for first variable
y=y+h*keulerf2; %Euler forward method for second variable
OUT=[t(j+1) x y]
endfor
endfunction
Example:
%Initial values:
t0=0;tf=3;
x0=10; %x(t0)
y0=10; %y(t0)
n=3;
OUT_0=[t0 x0 x0 y0 y0]
f1=@(t,x,y) [2*x 0]; %Equation 1 (arbitrary example): [dx/dt]=[2x 0]
f2=@(t,x,y) [2*y]; %Equation 2 (arbitrary example): [dy/dt]=[2y]
[t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)
%It only works for f1, f2 of 1x1 size. I don't quite know why the dimensions aren't being consistent.
Appreciate any feedback. Have a nice day.
If I understood it correctly, you should use matrix annotation A*x for your f1
This is the Euler:
function [t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)
h=(tf-t0)/n; %Constant step size
t=t0:h:tf;
x=[x0]; % also define your two starting values better outside this function
y=[y0]; %Starting values
for j=1:n
keulerf1=f1(t(j),x,y); %f1=dx/dt (from first equation)
keulerf2=f2(t(j),x,y); %f2=dy/dt (from second equation)
x=x+h*keulerf1; %Euler forward method for first variable
y=y+h*keulerf2; %Euler forward method for second variable
OUT=[t(j+1) x' y']
endfor
endfunction
This would be your function:
%Initial values:
t0=0;tf=3;
x0=[10 10]'; %x(t0)
y0=10; %y(t0)
n=3;
OUT_0=[t0; x0; y0; y0]
f1=@(t,x,y) [2 0; 0 0]*x; %Equation 1 (arbitrary example): [dx/dt]=A*x
f2=@(t,x,y) [2*y]; %Equation 2 (arbitrary example): [dy/dt]=[2y]
[t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.