Main Content

Substitute Elements in Symbolic Matrices

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

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

(A1,1A1,2A2,1A2,2)

Substitute the element A1,2 with a value 5. Assign the value directly by indexing into the matrix element.

A(1,2) = 5
A = 

(A1,15A2,1A2,2)

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

syms B [2 2]
B
B = 

(B1,1B1,2B2,1B2,2)

The generated elements B1,1, B1,2, B2,1, and B2,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 = 

(B1,1B1,2B2,14)

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 = 

(abcbcacab)

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 = 

(aa+1ca+1cacaa+1)

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 = 

(aa+1a+2a+1a+2aa+2aa+1)

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 = 

(132-12-32-121-32-1232-12111)

E = 

(3a+30003000-3)

Replace the symbolic parameter a with the value 1.

subs(E,a,1)
ans = 

(60003000-3)