You are on page 1of 11

# Solving 1 Order ODEs

st

Example Problem

Use ode23 and ode45 to solve the initial value problem for 1 st order ODE

Governing equation

Initial
and
let

condition: y(0)=1

K=4

Divide

## our governing equation by K

Solving Numerically

## A variety of ode solvers in MATLAB (table in CH13)

We will use the most common for this simple problem: ode45

## Essentially uses RK method (adaptive in that it modifies time

steps depending on how much the function is changing)

1.

## A function that holds the right hand side of our numerically

prepared equation

2.

3.

## Initial condition (ours is y(0)=1)

[t,y] = solver(odefun,tspan,y0)

1.

## fcn/handle that evaluates the right side of the

differential equation

2.

3.

## #1. fcn/handle that evaluates the right side of the

differential equation

Create

## a user-defined function and save it as fun1.m

function fout=fun1(t,y)
%this function accepts two inputs, calculates the
equation and returns the results into fout
K=4; %given
fout=-t*y/(K*sqrt(2-y^2)); %notice fout match
end

## How do we use our function file, fun1.m ?

Call
the function file, fun1, from your main m-file,
mainm.m

## clear all, close all, clc;

timerange=[0,5]; % #2
initialy=1; %

## [t,y]=ode45(@f,timerange,initialy); %notice @sign

%returns 2 things: a vector t set of times for which we calc ys; and a vector y
outputs a y at each of those corresponding times

## plot(t,y) %graphical view of solution

xlabel(t values from set);
ylabel(y values for each t);

## Alternatively, can use anonymous function

(all in one file)

mainm2.m
clear all, close all, clc; K=4; %given
f=@(t,y) -t*y/(K*sqrt(2-y^2)); %create an anonymous fcn to store RHS of ODE
timerange=[0,5]; % initialy=1; %

## [t1,y1]=ode45(f,timerange,initialy); %notice absence of @sign

plot(t1,y1) %graphical view of solution
xlabel(t values from set)
ylabel(y values for each t);

clear all, close all, clc; %This program compares ode45 & ode23 solvers
K=4;
f=@(t,y) -t*y/(K*sqrt(2-y^2)); %create an anonymous fcn to store RHS of ODE
timerange=[0,5]; %t?[0,5]
initialy=1; % initial conditions
[t1,y1]=ode45(f,timerange,initialy); %notice absence of @sign
subplot(2,1,1) %ode45 plot
plot(t1,y1,'r') %graphical view of solution
title('Solving dy/dt= -ty/K(2-y^2)^1^/^2 using ode45')
xlabel('t values from set'); ylabel('y values for each t'); legend('ode45')
subplot(2,1,2) %ode23 plot
[t2,y2]=ode23(f,timerange,initialy); %notice absence of @sign
plot(t2,y2) %graphical view of solution
title('Solving dy/dt= -ty/K(2-y^2)^1^/^2 using ode23')
xlabel('t values from set'); ylabel('y values for each t'); legend('ode23')

Solutions

What is y(3)?