How to call a variable matrix from one script to another script
Show older comments
I have two scripts. In first one i will get A and B matrices which are interms of theta as shown below.
sym theta
A = cos(theta).*[1 5 6;
2 9 3;
5 1 0]
B = tan(2*theta).*[8 5 1;
0 1 6;
2 4 7]
I want to use these A and B matrices in another script, which is given below
function dydt = scriptname(t, y)
theta = y(3); % Substitute y(3) in place of theta in A and B matrices
A % Extract A matrix
B % Extract B matrix
V = [1;
5;
3]
dydt = V-((A+B)*Y);
end
Finally i will plot these ODE's in another script that i didnt gave here.
My main doubt is how to extract A and B matrices(especially those are variable matrices) into another script.
After extracting these A and B matrices i will substitute y(3) so that i can get rid of theta.
I havent shown my exact problem because its too complicated. Focus on my main doubt dont care about values.
Thanks in advance.
Accepted Answer
More Answers (1)
The first code shows a "script", the second one a "function". While scripts share their variables with the callers automatically, functions don't. As far as I understand all you havt to do is to call the script:
% Script file: "yourScript.m"
sym theta
A = cos(theta).*[1 5 6;
2 9 3;
5 1 0]
B = tan(2*theta).*[8 5 1;
0 1 6;
2 4 7]
% Function file: "scriptname.m" ( missleading name! This is not a script.)
function dydt = scriptname(t, y)
theta = y(3); % Substitute y(3) in place of theta in A and B matrices
yourScript; % <-- A and B are defined internally
V = [1;
5;
3]
dydt = V-((A+B)*Y);
end
For productive code, scripts are a shot in your knee, because you cannot see directly, where the variables are defined. Use functions instead, to forward variables explicitly:
% Script file: "yourFunction.m"
function [A, B] = yourFunction()
sym theta
A = cos(theta).*[1 5 6;
2 9 3;
5 1 0]
B = tan(2*theta).*[8 5 1;
0 1 6;
2 4 7]
end
% Function file: "theOtherFunction.m"
function dydt = theOtherFunction(t, y)
[A, B] = yourFunction();
V = [1;
5;
3]
dydt = V-((A+B)*Y);
end
7 Comments
Bathala Teja
on 7 Sep 2021
Jan
on 7 Sep 2021
Then:
function dydt = theOtherFunction(t, y)
persistent A B
if isempty(A)
[A, B] = yourFunction();
end
V = [1;
5;
3]
dydt = V-((A+B)*Y);
end
Now A and B are created once only. To reset the persistently stored variables:
clear theOtherFunction
Bathala Teja
on 7 Sep 2021
Fabio Freschi
on 7 Sep 2021
You can find an explanation of persistent and its usage here
Bathala Teja
on 7 Sep 2021
Fabio Freschi
on 7 Sep 2021
when you create A you create B s well, so you must check only one of them
Bathala Teja
on 7 Sep 2021
Categories
Find more on Numeric Solvers in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!