Main Content

Find Symbolic Variables in Expressions, Functions, and Matrices

To find symbolic variables in an expression, function, or matrix, use symvar. For example, find all symbolic variables in symbolic expressions f and g:

syms a b n t x
f = x^n;
g = sin(a*t + b);
ans =
[ n, x]

Here, symvar sorts all returned variables alphabetically. Similarly, you can find the symbolic variables in g by entering:

ans =
[ a, b, t]

symvar also can return the first n symbolic variables found in a symbolic expression, matrix, or function. To specify the number of symbolic variables that you want symvar to return, use the second parameter of symvar. For example, return the first two variables found in symbolic expression g:

symvar(g, 2)
ans =
[ b, t]

Notice that the first two variables in this case are not a and b. When you call symvar with two arguments, it finds symbolic variables by their proximity to x before sorting them alphabetically.

When you call symvar on a symbolic function, symvar returns the function inputs before other variables.

syms x y w z
f(w, z) = x*w + y*z;
ans =
[ w, z, x, y]

When called with two arguments for symbolic functions, symvar also follows this behavior.

symvar(f, 2)
ans =
[ w, z]

Find a Default Symbolic Variable

If you do not specify an independent variable when performing substitution, differentiation, or integration, MATLAB® uses a default variable. The default variable is typically the one closest alphabetically to x or, for symbolic functions, the first input argument of a function. To find which variable is chosen as a default variable, use the symvar(f, 1) command. For example:

syms s t
f = s + t;
symvar(f, 1)
ans =
syms sx tx
f = sx + tx;
symvar(f, 1)
ans =

For more information on choosing the default symbolic variable, see symvar.