## Matlab

Moderators: None (Apply to moderate this forum)
Number of posts: 2174

This Forum Only

Basic Matlab Question with ode45 Posted by airwalkery2k on 11 Mar 2009 at 9:22 AM
Hi,

I am using Matlab for a class, and unfortunately, I don't have much experience in it.

For my problem, I need to solve an ordinary differential equation using Matlab's built-in ODE45 function. Using some tutorials, I came up with the following code to solve and plot my function.

function jtd
[t,x] = ode45(@dfile,[0,20],[0;0]);
plot(t,x(:,1))
title('nonlinear')
xlabel('t'), ylabel('y'), grid
function xprime = dfile(t,x)
F=13.4;
a=0.1;
xprime = zeros(2,1);
xprime(1) = x(2);
xprime(2) = F*cos(t) - a*x(2) - x(1)^3;

It works well, but I need to be able to vary F and a using a loop to get multiple plots as the two variables change. Yet I can't for the life of me figure out how to get a variable from the main function JTD into the function xprime when I call the ode45 function.

If I could figure that out, it would help me immensely in continueing my program.
Re: Basic Matlab Question with ode45 Posted by giug on 11 Mar 2009 at 1:34 PM
You can rewrite the code in this way:

F=13.4;
a=0.1;
fun=@(x,t) dfile(x,t,F,a);

[t,x] = ode45(fun,[0,20],[0;0]);
plot(t,x(:,1))
title('nonlinear')
xlabel('t'), ylabel('y'), grid

function xprime = dfile(t,x,F,a)
xprime = zeros(2,1);
xprime(1) = x(2);
xprime(2) = F*cos(t) - a*x(2) - x(1)^3;

I define the function handle of dfile out of the ode45 function. In this way you can pass the parameter to the function.

Now you can make a for cicle to make different plots, for example:
F=[12.3 13.4];
a=[0.2 0.1];
for i=1:length(F)
figure();
fun=@(x,t) dfile(x,t,F(i),a(i));
...
end

I add the function figure() so that plots on different figures.
Re: Basic Matlab Question with ode45 Posted by airwalkery2k on 11 Mar 2009 at 2:08 PM
That worked like a charm, except for the function name being chopped off, in case anybody reading decides to copy and paste what you wrote for me.

From here on out, it should be smooth sailing. Thanks, Giug!
Re: Basic Matlab Question with ode45 Posted by giug on 11 Mar 2009 at 2:28 PM
I'm happy that it runs as you wanted!
Re: Basic Matlab Question with ode45 Posted by squashinmonks on 16 Mar 2010 at 1:21 PM
How would removing the cos(t) change the code? I am doing something similar but in my diff eqns there are no cos(t) or anything similar.

## Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic