How to extract variable from a function file while using ode45?
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
x = [0.8 -0.2 1 0 0 0.8 -0.2]';
tspan = [0 20];
[t,x]= ode45(@(t,x) fun(t,x),tspan,x);
function [dot] = fun(t,x)
k1 = 3;
k2 = 3;
k3 = 3;
x1 = x(1);
x2 = x(2);
x3 = x(3);
z2 = x(4);
z3 = x(5);
S1 = x(6);
S2 = x(7);
yr = sin(t);
s1 = x1 - yr;
s2 = x2 - z2;
s3 = x3 - z3;
tau2 = exp(-t) + 0.05;
tau3 = exp(-t) + 0.05;
alpha2 = -k1*s1 - (x1^2 + x2^3 +x3 -x2) + cos(t);
z2dot = (alpha2 - z2)/tau2;
alpha3 = -k2*s2 - (x1^2*x2 + x3^5 - x3) + z2dot;
z3dot = (alpha3 - z3)/tau3;
u = -k3*s3 - x1*x2*x3^2 + z3dot;
x1dot = x1^2 + x2^3 + x3;
x2dot = x1^2*x2 + x3^5;
x3dot = u + x1*x2*x3^2;
S1dot = x1dot - cos(t);
S2dot = x2dot - z2dot;
dot = [x1dot x2dot x3dot z2dot z3dot S1dot S2dot]';
For example, I want to extract variable u from this code, is it possible to do so?
1 Commento
Jan
il 20 Mar 2021
Please use the tools for formatting code in the forum. I've done this for you this time.
Risposta accettata
Jan
il 20 Mar 2021
Modificato: Jan
il 20 Mar 2021
This question is asked several times per day. I ask MathWorks to include an explanation in the documentation.
Yes, of course it is possible. Simply modify the function to be integrated such, that it accepts vectors as input and use the output of ODE45 as input. There is a tricky need to transpose the inputs:
[t, x] = ode45(@fun, tspan, x); % @fun is faster than @(t,x) fun(t,x)
[~, u] = fun(t.', x.');
function [dot, u] = fun(t, x)
k1 = 3;
k2 = 3;
k3 = 3;
x1 = x(1, :);
x2 = x(2, :);
x3 = x(3, :);
... etc.
% Use elementwise operators: * ==> .* , ^ ==> .^ , / ==> ./
end
0 Commenti
Più risposte (1)
prabhjeet singh
il 20 Mar 2021
7 Commenti
Jan
il 22 Mar 2021
"if I edit code as per your suggestion" - this still does not allow to understand, what you are doing to obtain different values for yr. You just show one of the methods, but what is the other?
[~ , u, yr] = fun(t.', x.');
figure;
plot(t, yr);
hold on
plot(t, sin(t), 'ro');
function [dot,u,yr] = fun(t,x)
...
yr = sin(t);
...
end
Except for transposition of the vector both outputs are equal.
You questions about Matlab are welcome in this forum. You do not "bother", but try to solve a problem. This is the purpose of this forum and if I do not find the time to assist you, somebody else will do this.
Vedere anche
Categorie
Scopri di più su Function Creation 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!