Changing a variable when calling a function
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Jesse Olson
il 2 Ott 2018
Modificato: Stephen23
il 2 Ott 2018
So I have a value 'r' that I'm trying to change from a constant (r=5) to time-dependent (r=1.5*t) when I call a function and redefine 'r'. So far, no luck, I'm new at MATLAB and still don't know a lot of syntax. Here's one of my attempts (the third plot has the changing r):
%function file:
function ydot = ode5_39 (t,y,r)
r=5;
L = 1;
g = 9.81;
ydot(1) = y(2);
ydot(2) = (1/L)*(r*cos(y(1))-g*sin(y(1)));
ydot=ydot';
%plot file:
[t,y,r]=ode45('ode5_39', [0 10], [0.5 0]);
subplot(3,1,1);
plot(t,y(:,1));
ylim([-0.5 1]);
hold on
plot(t,y(:,2));
title('part (a)')
legend('x','xdot');
[t,y,r]=ode45('ode5_39', [0 10], [3 0]);
subplot(3,1,2);
plot(t,y(:,1));
hold on
plot(t,y(:,2));
title('part (b)')
legend('x','xdot');
[t,y,r]=ode45('ode5_39', [0 10], [3 0]);
r=1.5*t;
subplot(3,1,3);
plot(t,y(:,1));
hold on
plot(t,y(:,2));
title('part (c)')
legend('x','xdot');
1 Commento
KALYAN ACHARJYA
il 2 Ott 2018
You assigned r=5 within the function, also you listed r in the function inputs lists, why??
Risposta accettata
Walter Roberson
il 2 Ott 2018
function ydot = ode5_39 (t, y, rf, rc)
r = rf*t + rc;
L = 1;
g = 9.81;
ydot(1) = y(2);
ydot(2) = (1/L)*(r*cos(y(1))-g*sin(y(1)));
ydot=ydot';
with
[t, y] = ode45(@(t,y) ode5_39(t, y, 0, 5), [0 10], [0.5 0]); %r = 0*t + 5
and
[t, y] = ode45(@(t,y) ode5_39(t, y, 1.5, 0), [0 10], [3 0]); %r = 1.5*t + 0
If you wanted something more complicated than linear for finding r, then probably the easiest way to do that would be to use an anonymous function. No point in describing that unless you need it, though.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!