# Substitute Elements in Symbolic Matrices

Create a 2-by-2 matrix A with automatically generated elements using sym. The generated elements ${A}_{1,1}$, ${A}_{1,2}$, ${A}_{2,1}$, and ${A}_{2,2}$ do not appear in the MATLAB® workspace.

A = sym('A',[2 2])
A =

$\left(\begin{array}{cc}{A}_{1,1}& {A}_{1,2}\\ {A}_{2,1}& {A}_{2,2}\end{array}\right)$

Substitute the element ${A}_{1,2}$ with a value 5. Assign the value directly by indexing into the matrix element.

A(1,2) = 5
A =

$\left(\begin{array}{cc}{A}_{1,1}& 5\\ {A}_{2,1}& {A}_{2,2}\end{array}\right)$

Alternatively, you can create a 2-by-2 matrix using syms. Create a matrix B using syms.

syms B [2 2]
B
B =

$\left(\begin{array}{cc}{B}_{1,1}& {B}_{1,2}\\ {B}_{2,1}& {B}_{2,2}\end{array}\right)$

The generated elements ${B}_{1,1}$, ${B}_{1,2}$, ${B}_{2,1}$, and ${B}_{2,2}$ appear as symbolic variables B1_1, B1_2, B2_1, and B2_2 in the MATLAB workspace. Use subs to substitute the element of B by specifying the variable name. For example, substitute B2_2 with 4.

B = subs(B,B2_2,4)
B =

$\left(\begin{array}{cc}{B}_{1,1}& {B}_{1,2}\\ {B}_{2,1}& 4\end{array}\right)$

You can also create a matrix by specifying the elements individually. Create a 3-by-3 circulant matrix M.

syms a b c
M = [a b c; b c a; c a b]
M =

$\left(\begin{array}{ccc}a& b& c\\ b& c& a\\ c& a& b\end{array}\right)$

Replace variable b in the matrix M by the expression a + 1. The subs function replaces all b elements in matrix M with the expression a + 1.

M = subs(M,b,a+1)
M =

$\left(\begin{array}{ccc}a& a+1& c\\ a+1& c& a\\ c& a& a+1\end{array}\right)$

Next, replace all elements whose value is c with a + 2. You can specify the value to replace as c, M(1,3) or M(3,1).

M = subs(M,M(1,3),a+2)
M =

$\left(\begin{array}{ccc}a& a+1& a+2\\ a+1& a+2& a\\ a+2& a& a+1\end{array}\right)$

To replace a particular element of a matrix with a new value while keeping all other elements unchanged, use the assignment operation. For example, M(1,1) = 2 replaces only the first element of the matrix M with the value 2.

Find eigenvalues and eigenvectors of the matrix M.

[V,E] = eig(M)
V =

$\left(\begin{array}{ccc}1& \frac{\sqrt{3}}{2}-\frac{1}{2}& -\frac{\sqrt{3}}{2}-\frac{1}{2}\\ 1& -\frac{\sqrt{3}}{2}-\frac{1}{2}& \frac{\sqrt{3}}{2}-\frac{1}{2}\\ 1& 1& 1\end{array}\right)$

E =

$\left(\begin{array}{ccc}3 a+3& 0& 0\\ 0& \sqrt{3}& 0\\ 0& 0& -\sqrt{3}\end{array}\right)$

Replace the symbolic parameter a with the value 1.

subs(E,a,1)
ans =

$\left(\begin{array}{ccc}6& 0& 0\\ 0& \sqrt{3}& 0\\ 0& 0& -\sqrt{3}\end{array}\right)$

## Support

#### Mathematical Modeling with Symbolic Math Toolbox

Get examples and videos