Basic Matrix Operations and Functions in MATLAB Get Certified
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);
disp(A) produces a 1×9 row matrix:
1 2 3 4 5 6 7 8 9
disp(B) produces a 3×3 matrix:
1 2 3
4 5 6
7 8 9
Alternatively, you can create matrices using built-in MATLAB functions:
% Using functions to create matrices
Z = zeros(3,3); % 3×3 matrix of zeros
Q = eye(4); % 4×4 identity matrix
R = rand(3,3); % 3×3 matrix of random numbers
disp(Z);
disp(Q);
disp(R);
disp(Z) produces a 3×3 matrix of zeros:
0 0 0
0 0 0
0 0 0
disp(Q) produces a 4×4 identity matrix:
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.
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 (row-by-column) 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 (its determinant must be non-zero) for an inverse to exist.
Useful MATLAB Functions for Matrices
zeros(m,n) creates an m×n matrix filled with zeros.ones(m,n) creates an m×n matrix filled with ones.eye(n) creates an n×n identity matrix.size(A) returns the dimensions of matrix A as a vector [rows columns].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 an n×n matrix of random numbers uniformly distributed in (0,1).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.