symbolic function of a symbolic vector variable

I would like to define a symbolic function f, which takes as input a vector z. Then, it should add z to the vector y = [-1, 2, -1]. I am having trouble with this very elementary task.
Here is my code:
y = [-1, 2, -1];
z = sym('z',[1 3]);
syms f(z);
f(z) = y + z;
f([1,2,3])
The output should be [0, 4, 2], but I get:
ans =
1×3 cell array
{[0 1 2]} {[3 4 5]} {[0 1 2]}
Thank you in advance!

Réponses (2)

y = [-1, 2, -1];
syms f(z)
z = sym('z',[1 3]);
f(z) = y + z
f(z1, z2, z3) = 
f(1,2,3)
ans = 

1 commentaire

Notice that the function expanded to be a function of 3 arguments.

Connectez-vous pour commenter.

In MATLAB, a normal symbolic variable always stands in for a scalar, and calculation is done as-if it is a scalar. So for example,
y = [-1, 2, -1];
syms z
A = y + z
A = 
Notice that z + y was treated as implicit expansion between the scalar z and the vector y, giving a vector result. If you then substituted a vector for z, the vector would be substituted into each position of A.
You can also create variables at the MATLAB level that are vectors or arrays of scalar symbolic variables
syms Z [1 3]
Z
Z = 
B = y + Z
B = 
f(Z) = B
f(Z1, Z2, Z3) = 
each position in Z became a scalar variable, and then the vector of length 3 plus the vector of length 3 in y gives a vector output. But notice that when you put a vector variable in as the defining argument of a symbolic function, that it expands to multiple arguments. It is not possible to define a symbolic function that names a single symbolic variable but treats the variable as a vector for calculation purposes -- no f(z) = z(1)^2 + 2*z(2) for example
It is also possible in MATLAB to create symbolic matrices that get named together, such as
V = symmatrix('V', [1 3])
V = 
C = V + y
C = 
Notice that V is retained as a single name even though it is a 1 x 3 vector -- unlike above in B where Z expanded to
However... you cannot use a symbolic matrix as the defining parameter to a function
g(V) = C
Check for incorrect argument data type or missing argument in call to function 'symmatrix2sym'.

Error in indexing (line 179)
Z = symmatrix(subsasgn(symmatrix2sym(L), R, varargin{:}));
In short, what you want to do cannot be done in MATLAB.

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by