Skip to content

MATLAB - Matrix

In MATLAB, the fundamental data type is the array. A matrix is simply a two-dimensional array, but MATLAB’s capabilities extend to arrays with any number of dimensions. Understanding how to create, manipulate, and access array data is the most critical skill for any MATLAB user.

You can create a matrix by entering elements in each row, separated by commas or spaces, and using a semicolon (;) to mark the end of each row. All elements are enclosed in square brackets [].

For example, let’s create a 4-by-5 matrix A:

% The semicolon at the end of the line suppresses the output.
A = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
% To display the matrix, just type its name:
A

MATLAB will execute the above statement and return the following result:

A =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

Using Built-in Functions for Array Creation

Section titled “Using Built-in Functions for Array Creation”

Manually creating large matrices is tedious. MATLAB provides functions to generate common types of matrices:

% Create a 3x3 matrix of all zeros
Z = zeros(3, 3);
% Create a 2x4 matrix of all ones
O = ones(2, 4);
% Create a 4x4 identity matrix (ones on the diagonal)
I = eye(4);
% Create a 3x5 matrix of uniformly distributed random numbers
R = rand(3, 5);
% Create a 3x5 matrix of normally distributed random numbers
N = randn(3, 5);

Indexing is the way you select specific elements from an array. MATLAB is a 1-based indexing language, meaning the first element is at index 1, not 0.

To reference an element in the m-th row and n-th column of a matrix A, you use the syntax A(m, n).

% Let's use the matrix A from before
A = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
% Get the element in the 2nd row, 5th column
element = A(2, 5)

MATLAB will return:

element = 6

The colon operator : is extremely powerful. It can be used to select entire rows, columns, or ranges.

% Get all elements in the 4th column
col_4 = A(:, 4);
% Get all elements in the 3rd row
row_3 = A(3, :);
% Get a submatrix from rows 2-3 and columns 2-4
submatrix = A(2:3, 2:4);
% Get all elements from the 3rd column to the end
last_cols = A(:, 3:end); % 'end' is a keyword for the last index

The submatrix example will produce:

submatrix =
3 4 5
4 5 6

Logical indexing is a highly efficient and readable technique. You create a logical array (containing true and false values) of the same size as your data and use it to select elements where the index is true.

% Find all elements in matrix A that are greater than 5
large_values = A(A > 5)
% This returns a column vector of the values that satisfy the condition.
% You can also use it to modify values
% Replace all odd numbers with 0
A_modified = A;
% rem(A, 2) == 1 creates a logical mask for odd numbers
A_modified(rem(A_modified, 2) == 1) = 0;

You can delete an entire row or column by assigning an empty array [] to it.

% Create a fresh copy of the matrix
A_temp = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
% Delete the 4th row
A_temp(4, :) = [];
% Now A_temp is a 3x5 matrix.
% Delete the 5th column
A_temp(:, 5) = [];
% Now A_temp is a 3x4 matrix.

You can build larger matrices by concatenating smaller ones. Let’s create a 4-by-3 matrix by duplicating and stacking the second and third rows of an existing matrix.

% Original 3x3 matrix
a = [1 2 3; 4 5 6; 7 8 9];
% We want rows 2 and 3, then rows 2 and 3 again
% Create a vector of the row indices we want
index_vector = [2, 3, 2, 3];
% Use this vector to create the new matrix
new_mat = a(index_vector, :)

The result is a new matrix constructed in the specified order:

new_mat =
4 5 6
7 8 9
4 5 6
7 8 9

Here’s a brief overview of essential matrix operations. A critical concept is the difference between matrix operations (which follow the rules of linear algebra) and element-wise operations (which apply an operation to each element independently).

  • Addition and Subtraction (+, -): These are always element-wise. The matrices must have the same dimensions. C = A + B
  • Matrix Multiplication (*): Follows linear algebra rules. The number of columns in the first matrix must equal the number of rows in the second. C = A * B
  • Element-wise Multiplication (.*): Multiplies corresponding elements. The matrices must have the same dimensions. C = A .* B
  • Matrix Division (\, /): Solves systems of linear equations. x = A\b is a more robust way of solving A*x = b.
  • Element-wise Division (./): Divides corresponding elements. C = A ./ B
  • Transpose ('): Flips the matrix over its diagonal. B = A'
  • Determinant (det): A scalar value computed from a square matrix. d = det(A)
  • Inverse (inv): For a square matrix A, its inverse B is such that A*B is the identity matrix. B = inv(A). Note: Using inv is often less accurate and slower than using the backslash operator (\) for solving equations.

Pre-allocation: If you know the final size of a matrix you’re building in a loop, pre-allocate it with zeros() or ones() before the loop. This is significantly faster than growing the array in each iteration.

Modern Data Structures: For mixed data (numbers, text, categories), consider using table or timetable objects. They provide named columns and are more flexible than purely numeric matrices for data analysis tasks.