MATLAB: The Body of A Symbolic Function

symbolic

Why this code runs well
syms x y
f(x,y)=x+1
f(x, y) =
x + 1
while this one is wrong?
s(x,y)=1
错误使用 sym/subsindex (line 766)
Invalid indexing or function definition. When defining a function, ensure that the arguments are
symbolic variables and the body of the function is a SYM expression. When indexing, the input
must be numeric, logical, or ':'.
in this case, how can I get a function of two variables that always equals a const?

Best Answer

Think about how the MATLAB parser sees it.
syms x y
s(x,y) = 1
Error using sym/subsindex (line 766)
Invalid indexing or function definition. When defining a function, ensure that the arguments are symbolic variables and the body of the function is
a SYM expression. When indexing, the input must be numeric, logical, or ':'.
So it tried to do an indexed assignment above. Compare that to the following assignment.
s(x,y) = sym(1)
s(x, y) =
1
So the second case worked. Why? Because the right hand side was a sym already. In the first case, MATLAB thought you have some unknown thing called s. It saw the right hand side was a number. So it tried an assignment, trying to create a variable called s, with indices x and y. Of course that failed because x and y are syms.
In the second case, the parser was smart enough to realize that I was defining a symbolic function.
Related Question