This example shows how to use arithmetic operators on matrices. You can use these arithmetic operations to perform numeric computations.
MATLAB allows you to process all the values in a matrix using a single arithmetic operator or function.
Create a 3-by-3 matrix.
disp('Create 3-by-3 matrix a:') disp('>> a = [1 2 3; 4 5 6; 7 8 10]') a = [1 2 3; 4 5 6; 7 8 10]
Create 3-by-3 matrix a:
>> a = [1 2 3; 4 5 6; 7 8 10]
a =
1 2 3
4 5 6
7 8 10
You can add a scalar to each element of the matrix with a single operator.
disp('Add 10 to each matrix value:') disp('>> a + 10') a + 10
Add 10 to each matrix value:
>> a + 10
ans =
11 12 13
14 15 16
17 18 20
You can calculate the sine for each of those values using a single function.
disp('Calculate sine for each value of a:') disp('>> sin(a)') sin(a)
Calculate sine for each value of a:
>> sin(a)
ans =
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
To transpose a matrix, use a single quote (').
disp('Transpose a:') disp('>> a''') a'
Transpose a:
>> a'
ans =
1 4 7
2 5 8
3 6 10
You can also perform standard matrix multiplication, which computes the inner products between rows and columns, using the multiplication '*' operator. This example confirms that a matrix multiplied by its inverse returns the identity matrix.
disp('Multiply matrix a by its inverse:') disp('>> p = a*inv(a)') p = a*inv(a)
Multiply matrix a by its inverse:
>> p = a*inv(a)
p =
1.0000 0 0
0.0000 1.0000 0
0.0000 -0.0000 1.0000
To perform multiplication on each individual element, use the element-wise multiplication '.*' operator.
disp('Multiply matrix a by itself (element-wise):') disp('>> p = a.*a') p = a.*a
Multiply matrix a by itself (element-wise):
>> p = a.*a
p =
1 4 9
16 25 36
49 64 100