Foundations of computer programming in MATLAB — Array Operations

Matrix multiplication

Something we will often do is matrix multiplication.

A = [ 5 3 ; 2 0 ];
B = [ 1 0 ; 1 1 ];
C = [ 1 ; -1 ];
D = A * B;
E = A * C;
F = A * B * C;

Matrix inverse

And matrix inversion.

A_inverse_1 = inv(A);
A_inverse_2 = A^-1;
am_i_awesome = A_inverse_1 == A_inverse_2

Matrix transpose

Transpose it.

A_transpose_1 = transpose(A);     % transpose
A_transpose_2 = A.';              % transpose
A_transpose_1 == A_transpose_2    % true
A_conj_transpose = ctranspose(A); % conjugate transpose
A_conj_transpose = A';            % conjugate transpose

Element-wise operations

Some array operators act element-wise, meaning that the arrays on which it operates are considered element-by-element. This is in constrast to the array operations covered thus far. When element-wise operators perform on a set of arrays, the arrays must be of the same size!

Addition and subtraction

Whenever we add or subtract two arrays, we add or subtract their elements, which is exactly how matrix addition and subtraction work.

a1 = [ 1 2 3; 4 5 6 ];
a2 = [ 0 1 2; 1 1 1 ];
a3 = a1 + a2;
a4 = a1 - a2;
disp(a3);
disp(a4);

Multiplication and division

Array multiplication can be either matrix multiplication * (as covered above) or element-wise multiplication .*. The latter multiplies element-wise, as shown below.

a5 = [ 1 2 3 ];
a6 = [ 3 2 1 ];
a7 = a5 .* a6;  % [ 3 4 3 ]

We can also divide element-wise with the operator ./, but there is no proper meaning to the division of matrices. (Important note: you can use the / operator on two matrices A and B in MATLAB, but the result of A/B is not a “matrix division”, but a solution to the equation $x\,A = B$, if it exists, or the least-squares approximation of the solution.) Let’s try out the element-wise ./ division operator.

a8 = [ 8 9 10 ];
a9 = [ 2 3 5 ];
a10 = a8 ./ a9;   % [ 4 3 2 ]