Operations on Matrices

 

Arithmetic on Matrices

X = [10 20; 30 40]
Y = [1 2; 3 4]
Z = [1 2; 3 4; 5 6]
X + Y
>>
  11   22
  33   44
X * 2   % or  2 * X
>>
  20   40
  60   80
X + 5   % or  5 + X
>>
  15   25
  35   45
Z + 2   % or Z + 2 * ones(size(Z))
>>
  3   4
  5   6
  7   8

Note:
size(Z)
>>  3   2

ones(size(Z))
>>
  1   1
  1   1
  1   1
X^2
% Matrix power (Will work only when X is a square matrix)

Element wise operations:

.^   % element-wise power
.*   % element-wise multiplication
./   % element-wise division
X = [1 2; 3 4]
X.^2
>>
  1    4
  9   16

Note: Element wise operations can be done with scalars as well as with matrices.
A = [1 2; 3 4; 5 6]
B = [11 12; 13 14; 15 16]

A .* B
>>  11   24
    39   56
    75   96
A .* 3   % or 3 .* A  or A * 3
>>   3    6
     9   12
    15   18
1 ./ A
% element-wise reciprocal
>>
  1.00000   0.50000
  0.33333   0.25000
  0.20000   0.16667
log(A)
% element-wise logarithm
>>
  0.00000   0.69315
  1.09861   1.38629
  1.60944   1.79176
-A   % or  -1*A
>>  -1  -2
    -3  -4
    -5  -6
A + 1
>>  2   3
    4   5
    6   7

Matrix Multiplication:

A = randi([-5,5], 3, 4)   % or randi([-5,5], [3, 4])
>>
  -3    -4     0     4
   1     3     4     3
   5    -3    -2    -1

B = randi([-5,5], 4, 2)
>>
   0     5
  -1    -2
   3     2
   5    -1

C = A * B
>>
  24   -11
  24     4
  -8    28

C = B * A
>> ERROR: Nonconformant arguments

Other operations on Matrices

Transpose operator: A'

A = randi([-5,5], 2, 3)
>>
  2   1  -5
  5   0   1

A'
>>
   2   5
   1   0
  -5   1