MATLAB lessons N.2¶
A simple function used to test ode45
:
File* f.m
:open:
1% A comment is a line beginned with the '%' character
2%
3% Define the function f(x,y) = x^2 - y to be integrated
4% by a numerical solver of MATLAB
5%
6% A function is defined by the keyword function
7% followed by the prototype of the functions itself
8
9function res = f( x, y )
10 res = x^2 - y ;
11end
A simple function whise solution lie on a circle: File f1.m
:open:
1%
2% function for the definition of the ODE system
3%
4% y1'=y2
5% y2'=-y1
6% y1(0)=1
7% y2(0)=0
8%
9function res = f1( x, Y )
10 res = [ Y(2) ; -Y(1) ] ; % return a matrix with 2 row and 1 column
11end
Another example of ODE: File f3.m
:open:
1%
2% ODE:
3% y'=v
4% y'=exp(x)-v-y
5%
6function res = f3( x, Y )
7 % y = Y(1)
8 % v = Y(2)
9 res = [ Y(2) ; exp(x) - Y(1) - Y(2) ] ;
10end
An exact solution to test the code: File exact.m
:open:
1%
2% Exact solution for problem
3%
4% y'''(t) = -t - y(t)
5% y(0) = y'(0) = 0
6% y''(0) = 1
7%
8function res = exact( t )
9 res = -t + (2/sqrt(3))*exp(t/2).*sin((sqrt(3)/2)*t) ;
10end