Basic Matrix Operations and Functions in MATLAB
Matrices are fundamental to MATLAB, given that its name stands for MATrix LABoratory. This section introduces the basics of matrix creation, manipulation, and common operations.
Creating Matrices
Matrices can be created using square brackets with elements separated by spaces or commas, and rows separated by semicolons:
% Creating a matrix
A = [1 2 3 4 5 6 7 8 9];
B = [1 2 3; 4 5 6; 7 8 9];
disp(A);
disp(B);
1 2 3 4 5 6 7 8 9while, disp(B) will output a (3 x 3) row column matrix:
1 2 3 4 5 6 7 8 9
Alternatively, you can create matrices using MATLAB inbuilt functions:
% Using functions to create matrices
Z = zeros(3,3); % 3x3 matrix of zeros
Q = eye(4); % 4x4 identity matrix
R = rand(3,3); % 3x3 matrix of elements represented by random numbers
disp(Z);
disp(Q);
disp(R);
0 0 0 0 0 0 0 0 0while, disp(Q) will output a (4 x 4) row column matrix with ones on the diagonal and zeros elsewhere:
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
Matrix Operations
MATLAB provides several built-in functions and operators to perform operations on matrices. Here are a few examples:
Matrix Addition and Subtraction
% Adding and subtracting matrices
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A + B; % Matrix addition
D = A - B; % Matrix subtraction
disp(C);
disp(D);
Matrix Multiplication
% Matrix multiplication
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A * B; % Standard matrix multiplication
disp(C);
For element-wise multiplication, use the .*
operator:
% Element-wise multiplication
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A .* B;
disp(C);
Matrix Transpose
% Transposing a matrix
A = [1 2 3; 4 5 6];
B = A'; % Transpose of A
disp(B);
Matrix Inverse
% Finding the inverse of a matrix
A = [1 2; 3 4];
B = inv(A);
disp(B);
Note: Not all matrices have an inverse. A matrix must be square and non-singular for its inverse to exist.
Useful MATLAB Functions for Matrices
zeros(m,n)
creates an m x n
matrix filled with zeros.ones(m,n)
creates an m x n
matrix filled with ones.eye(n)
creates an n x n
identity matrix.size(A)
returns the size of matrix A
as a vector.length(A)
returns the length of the largest dimension of A
.det(A)
computes the determinant of a square matrix A
.inv(A)
computes the inverse of a square matrix A
.rank(A)
returns the rank of matrix A
.rand(N)
returns N x N
matrix of random numbers.Practice Questions
Test Yourself
1. Create a 3×3 matrix with random numbers and find its transpose.
2. Compute the determinant of a 2×2 matrix and check if it has an inverse.
3. Perform element-wise multiplication on two matrices.