How can I define a symbolic function with vector arguments?

4 views (last 30 days)
Radu Trimbitas on 13 Jan 2022
Commented: Walter Roberson on 20 Jan 2022
I wish to define a symbolic function with a vector argument, e.g.
f(x) = x(1)^2+x(2)^3+x(1)*sin(x(3))
How can I do this without introducing new variables (x must be a 3-dimensional colun vector)

Star Strider on 13 Jan 2022
A vector has only one dimension (that I am aware of), so I assume ‘x’ needs to be a (3x1) vector.
syms x % Declare 'x'
x = sym('x',[3,1]) % Create 'x' As A (3x1) Vector
x =
f(x) = x(1)^2+x(2)^3+x(1)*sin(x(3))
f(x1, x2, x3) =
Is this the desired result?
.
Walter Roberson on 20 Jan 2022
syms x
is the same as
x = sym('x');
assume(x, 'clear');
This creates a symbolic variable named x that lives inside the symbolic engine, and returns a coded reference to the MATLAB level and the coded reference is stored inside the MATLAB variable x . Then it extracts the coded reference from inside the MATLAB variable, and passes the coded reference to the symbolic engine along with instructions to clear any assumptions that may have been recorded against that variable.
x = sym('x',[3,1]) % Create 'x' As A (3x1) Vector
This creates symbolic variables x1, x2, x3 inside the symbolic engine and builds an internal vector of them, and returns a coded reference to the vector to the MATLAB level, where MATLAB stores it inside the MATLAB variable x, overwriting the reference to the symbolic engine variable x that was stored there. I would have to check references to see whether this form also clears assumptions. Unless you had a really good reason involving detailed knowledge of the symbolic engine, there would be no point in doing syms x before this.
x = [3; 5; 7]
This writes a numeric vector to the MATLAB variable x, discarding the reference to the symbolic vector that was stored there before. The reference to the symbolic vector is gone (but you can get it back if you know how.)
f(x) = x(1)^2 + x(2)^3 + x(1)*sin(x(3))
Remember that x at the MATLAB level is now a numeric vector. x at this point has no connection to the symbolic engine. So this is an assignment to a variable f indexed at the content of x -- so f(3), f(5), f(7) . That is why the output is 7 long.

Walter Roberson on 20 Jan 2022
You cannot do that in MATLAB.
You can use matlabFunction with the 'vars' option to generate a function handle that indexes into a vector argument. This will not, however, be a symbolic function.
The technology used for symbolic functions at the MATLAB level does not allow vector arguments to be created and indexed.
The internal symbolic engine does have indexing ability, and it is possible to create a function at the engine level. However, the MATLAB level cannot handle those objects...

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by