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)[A1_1, A1_2; A2_1, A2_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)[A1_1, sym(5); A2_1, A2_2]

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

syms B [2 2]
B = 

(B1,1B1,2B2,1B2,2)[B1_1, B1_2; B2_1, B2_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)[B1_1, B1_2; B2_1, sym(4)]

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)[a, b, c; b, c, a; c, a, b]

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)[a, a + 1, c; a + 1, c, a; c, a, a + 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)[a, a + 1, a + 2; a + 1, a + 2, a; a + 2, a, a + 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)[sym(1), sqrt(sym(3))/2 - sym(1/2), - sqrt(sym(3))/2 - sym(1/2); sym(1), - sqrt(sym(3))/2 - sym(1/2), sqrt(sym(3))/2 - sym(1/2); sym(1), sym(1), sym(1)]

E = 

(3a+30003000-3)[3*a + 3, sym(0), sym(0); sym(0), sqrt(sym(3)), sym(0); sym(0), sym(0), -sqrt(sym(3))]

Replace the symbolic parameter a with the value 1.

ans = 

(60003000-3)[sym(6), sym(0), sym(0); sym(0), sqrt(sym(3)), sym(0); sym(0), sym(0), -sqrt(sym(3))]