ode45 with multiple value for a single variable in a function file

function [ dudt ] = task3a_function( t,y )
w = 1
dudt = zeros(2,1)
dudt(1) = y(2)
dudt(2) = (10*sin(w*t))/3 - (75*y(1))/3
end
The value of w should be 1, 5, 10
and this is the ode45 file
tspan = [0 20]
initialvalues = [0 0]
fname ='task3a_function'
[t,y] = ode45(fname,tspan,initialvalues)
figure (1) % w = 1
plot(t,y(:,1)) % w = 1
figure (2) % w = 5
plot(t,y(:,1)) % w = 5
figure (3) % w = 10
plot(t,y(:,1)) % w = 10
Anyone can tell me how to get the 3 graph for w = 1, 5,10 respectively.
Thank you

 Akzeptierte Antwort

I would use a loop:
task3afunction = @(t,y,w) [y(2); (10*sin(w*t))/3 - (75*y(1))/3 ];
tspan = [0 20];
initialvalues = [0 0];
w = [1, 5, 10];
for k1 = 1:length(w)
[t{k1},y{k1}] = ode45(@(t,y)task3afunction(t,y,w(k1)),tspan,initialvalues);
figure(k1)
plot(t{k1},y{k1})
title(sprintf('w = %d',k1))
end
There’s no easy way to describe this without writing the code. However, you’ve done most of it yourself already.

6 Kommentare

Thank a lot
What if there were two parameters to be varied that is two for loops?How would one go about this?
@Suchetana Mitra — That depends entirely on what you want to do. If you use ndgrid to create a matrix of the combinations of the two parameters, you can do it in one loop.
A partial example —
p1 = 1:3;
p2 = 4:7;
[P1,P2] = ndgrid(p1,p2)
P1 = 3×4
1 1 1 1 2 2 2 2 3 3 3 3
P2 = 3×4
4 5 6 7 4 5 6 7 4 5 6 7
Pm = [P1(:) P2(:)]
Pm = 12×2
1 4 2 4 3 4 1 5 2 5 3 5 1 6 2 6 3 6 1 7
That one ‘Pm’ matrix will have every combination of both parameters, so only one loop will be necessary.
The ndgrid function can handle more than two argument vectors (the reason I chose it here), and the ‘Pm’ matrix would be similar regardless of how many parameters were defined as vector arguments to it, however that would still only require one loop.
Passing the extra parameters would simply mean indexing into the matrix. That could be done in the loop prior to calling the ode integration function (ode45 or whichever would be appropriate) or in the ordinary differential equation function itself, after passing each row of ‘Pm’ as a single argument.
.
Thanks! I will try
My pleasure!
A Vote would be appreciated!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by