Using loop for calculating ode with different parameter

How can I create a cycle, where I would use ode45 and be able to get a solution for 3 different values of a constant k so I don't have to change it manually.
example k=1 --> solution, then k=10 --> solution etc.
At the end, I would need to put all solutions into the same plot to compare.

回答(1 个)

Use a for loop. If k is non-linear, just put your values of interest into a vector.
loop_i = 0;
for k = [1 10 ....Rest of your numbers];
loop_i = loop_i+1;
[t{loop_i}, y{loop_i}] = ode45(...Whatever involving k);
end
I have to admit I don't know what size outputs the function ode45() will return, so sticking them in cells was simply a safe bet for me. If you always expect the same size vector to be returned, you could use y(:,loop_i) instead, or y(:,:,loop_i), etc. If y(:,loop_i) works for you, plotting will be as easy as plot(t,y).

5 个评论

If you pass a tspan of length 2 to ode45 then it returns a variable number of results. If you pass a tspan of length 3 or more to ode45 then it returns something with that many rows, one row per time requested.
Thanks the loop work, however the results are in matrix as a set of 1444x4 in 1x3 matrix (I used k= 1 10 100, so thats why 3 sets). How can I assign i.e. x to 1st column in this set?
@Martin: You will probably want to use this instead in your loop so you don't have to deal with cells:
%This results in y being 1444 x 4 x 3
[t(:,:,loop_i), y(:,:,loop_i)] = ode45(...Whatever involving k);
Then assigning columns could be as simple as
x = y(:,1,:); % Results in a 1444 x 1 x3
If you need to remove the singleton dimension, check out the squeeze() or permute() functions.
Thanks, this works perfectly, however new problem occured. I have defined k=1 in function. when I use loop it give 3 same results and not taking in account the k = [1 10 100] in loop. How can I change it?
Pass k into your ODE function (the first input to the ODE solver) as an additional parameter. The description of the odefun input argument in the documentation for ode45 contains a link "Parameterizing Functions" that describes various techniques you can use to do that.

请先登录,再进行评论。

类别

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by