Using subs() in a function when symbolic variables defined in another function

34 views (last 30 days)
Hello Everyone! I'm having some problems using the subs() function and I need your help.
I defined a function to calculate a jacobian matrix using symbolic variables. For example:
function myJacobian = getJacobian()
% Define function variables
syms x y z
% Define myFunction
myFunction = x^2 + y^2 + z^2;
% Calculate myJacobian
myJacobian = jacobian(myFunction, [x,y,z]);
end
Now, in "main", I am calling this function and obtaining the jacobian. Then, I am substituting the symbolic variables (x,y,z) with some numbers in another function
% Get the jacobian matrix F
F = getJacobian;
% Get my result
value_F = someRandomFunc(F, someOtherInputs);
where "someRandomFunc" is given as
function value_F = someRandomFunc(F)
currentX = getX(someRandomInputs1);
currentY = getY(someRandomInputs2);
currentZ = getZ(someRandomInputs3);
value_F = subs(F, {x,y,z}, {currentX,currentY,currentZ});
end
However, I am getting the following error
"Unrecognized function or variable 'x'."
I know that I am getting this error because these symbolic variables are not defined in the workspace of "someRandomFunc". So my question is that it is possible to transfer these symbolic variables defined in "getJacobian()" function to "someRandomFunc" so that I can use subs() with complacency. I tried to simplify my functions so that you can understand the problem better. My "somRandomFunc" function is in a for loop. At every iteration I am obtaining different x,y,z values and calculating the jacobian for this specific iteration accordingly. I do not want to define symbolic variables in "someRandomFunc" since it slows down the program a lot. Thanks for the help in advance.
Kind regards.

Accepted Answer

Paul
Paul on 25 Sep 2022
Making F into a symfun seems to work ....
F = getJacobian
F(x, y, z) = 
valueF = someRandomFunc(F)
valueF = 
function myJacobian = getJacobian()
% Define function variables
syms x y z
% Define myFunction
myFunction = x^2 + y^2 + z^2;
% Calculate myJacobian
myJacobian(x,y,z) = jacobian(myFunction, [x,y,z]);
end
function value_F = someRandomFunc(F)
currentX = 1;
currentY = 2;
currentZ = 3;
value_F = F(currentX,currentY,currentZ);
end
  4 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by