solve a first order de in matlab

MATLAB has a built-in function called ode45 that can be used to solve first order differential equations.

The syntax for using ode45 is as follows:

[t,y]=ode45(odefun,tspan,y0)
29 chars
2 lines

Here, odefun is a function handle to the function that describes the differential equation, tspan is a vector of time points at which the solution will be computed, and y0 is the initial condition of the equation.

For example, suppose we want to solve the following first order differential equation:

main.m
dy/dt = t*y, y(0) = 1
22 chars
2 lines

We can define the function that describes the differential equation as follows:

function dydt = myodefun(t,y)
dydt = t*y;
end
46 chars
4 lines

Then, we can use ode45 to solve the equation as follows:

tspan = [0 10]; % time span to compute solution
y0 = 1; % initial condition
[t,y] = ode45(@myodefun,tspan,y0); % solve the equation
132 chars
4 lines

The variable t will contain the time points at which the solution was computed, and the variable y will contain the corresponding values of y.

We can plot the results using the following code:

plot(t,y)
xlabel('t')
ylabel('y')
34 chars
4 lines

This will produce a plot of the solution to the differential equation.

gistlibby LogSnag