Method on @sym: subs (f, x, y)
Method on @sym: subs (f, y)
Method on @sym: subs (f)

Replace symbols in an expression with other expressions.

Example substituting a value for a variable:

syms x y
f = x*y;
subs(f, x, 2)
  ⇒ ans = (sym) 2⋅y

If x is omitted, symvar is called on f to determine an appropriate variable.

x and y can also be vectors or lists of syms to replace:

subs(f, {x y}, {sin(x) 16})
  ⇒ ans = (sym) 16⋅sin(x)

F = [x x*y; 2*x*y y];
subs(F, {x y}, [2 sym(pi)])
  ⇒ ans = (sym 2×2 matrix)

      ⎡ 2   2⋅π⎤
      ⎢        ⎥
      ⎣4⋅π   π ⎦

With only one argument, subs(F) will attempt to find values for each symbol in F by searching the workspace:

f = x*y
  ⇒ f = (sym) x⋅y

x = 42;
f
  ⇒ f = (sym) x⋅y

Here assigning a numerical value to the variable x did not change the expression (because symbols are not the same as variables!) However, we can automatically update f by calling:

subs(f)
  ⇒ ans = (sym) 42⋅y

Warning: subs cannot be easily used to substitute a double matrix; it will cast y to a sym. Instead, create a “function handle” from the symbolic expression, which can be efficiently evaluated numerically. For example:

syms x
f = exp(sin(x))
  ⇒ f = (sym)

       sin(x)
      ℯ

fh = function_handle(f)
  ⇒ fh =

      @(x) exp (sin (x))

fh(linspace(0, 2*pi, 700)')
  ⇒ ans =
      1.0000
      1.0090
      1.0181
      1.0273
      1.0366
      ...

Note: Mixing scalars and matrices may lead to trouble. We support the case of substituting one or more symbolic matrices in for symbolic scalars, within a scalar expression:

f = sin(x);
g = subs(f, x, [1 sym('a'); pi sym('b')])
  ⇒ g = (sym 2×2 matrix)

      ⎡sin(1)  sin(a)⎤
      ⎢              ⎥
      ⎣  0     sin(b)⎦

When using multiple variables and matrix substitions, it may be helpful to use cell arrays:

subs(y*sin(x), {x, y}, {3, [2 sym('a')]})
  ⇒ ans = (sym) [2⋅sin(3)  a⋅sin(3)]  (1×2 matrix)

subs(y*sin(x), {x, y}, {[2 3], [2 sym('a')]})
  ⇒ ans = (sym) [2⋅sin(2)  a⋅sin(3)]  (1×2 matrix)

Caution, multiple interdependent substitutions can be ambiguous and results may depend on the order in which you specify them. A cautionary example:

syms y(x) A B
u = y + diff(y, x)
  ⇒ u(x) = (symfun)
             d
      y(x) + ──(y(x))
             dx

subs(u, {y, diff(y, x)}, {A, B})
  ⇒ ans = (sym) A

subs(u, {diff(y, x), y}, {B, A})
  ⇒ ans = (sym) A + B

Here it would be clearer to explicitly avoid the ambiguity by calling subs twice:

subs(subs(u, diff(y, x), B), y, A)
  ⇒ ans = (sym) A + B

See also: @sym/symfun.

Package: symbolic