Basic Matlab Question with ode45 - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Basic Matlab Question with ode45

airwalkery2kairwalkery2k Posts: 2Member

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.

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

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.


  • giuggiug Posts: 217Member
    You can rewrite the code in this way:

    fun=@(x,t) dfile(x,t,F,a);[/b]
    [t,x] = ode45([b]fun[/b],[0,20],[0;0]);
    xlabel('t'), ylabel('y'), grid

    function xprime = dfile(t,x,[b]F,a[/b])
    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)
    fun=@(x,t) dfile(x,t,F(i),a(i));

    I add the function figure() so that plots on different figures.
  • airwalkery2kairwalkery2k Posts: 2Member
    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. [b]Thanks, Giug![/b]
  • giuggiug Posts: 217Member
    I'm happy that it runs as you wanted!
  • squashinmonkssquashinmonks Posts: 1Member
    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.
Sign In or Register to comment.