Matrices and N-d arrays
The array is MATLAB’s fundamental datum and the substance of nearly every page in this volume. A scalar is a 1×1 array, a vector is 1×N or N×1, a matrix is M×N, and an N-d array may have arbitrarily many dimensions. The language’s distinctive features — vectorisation, implicit expansion, the linear-algebra operators — flow from the fact that the array is the default container and that operations on arrays are first-class.
Constructing arrays
The most common form is the bracketed literal. Commas or whitespace separate row elements; semicolons or newlines separate rows:
v = [1 2 3 4 5]; % 1×5 row vector
w = [1; 2; 3; 4; 5]; % 5×1 column vector
A = [1 2 3
4 5 6]; % 2×3 matrix
The colon operator constructs an arithmetic progression:
1:10 % 1×10 row vector [1 2 ... 10]
0:0.1:1 % 1×11 row vector with step 0.1
10:-2:0 % 1×6 row vector [10 8 6 4 2 0]
A family of constructor functions builds arrays of given shape:
| Function | Produces |
|---|---|
zeros(m, n) | M×N array of zeros |
ones(m, n) | M×N array of ones |
eye(n) | N×N identity matrix |
nan(m, n) | M×N array of NaN |
true(m, n) | M×N logical, all true |
rand(m, n) | M×N uniform random in [0, 1) |
randn(m, n) | M×N standard normal random |
randi(k, m, n) | M×N uniform integer in 1:k |
linspace(a, b, n) | 1×N evenly spaced from a to b inclusive |
logspace(a, b, n) | 1×N evenly spaced in log10 |
magic(n) | N×N magic square |
repmat(A, m, n) | Tile A into M×N blocks |
The single-argument form zeros(n) produces N×N; longer forms — zeros(2, 3, 4) — produce N-d arrays. The functions accept a trailing class specifier — zeros(3, 'int32') — and the convenience form zeros(size(A)) matches an existing array’s shape.
Shape introspection
A = rand(2, 3, 4);
size(A) % [2 3 4]
size(A, 2) % 3 (size along dim 2)
[m, n, p] = size(A); % m=2, n=3, p=4
numel(A) % 24
ndims(A) % 3
length(A) % 4 (largest dimension)
isempty, isvector, iscolumn, isrow, ismatrix, and isscalar are the shape predicates. The function squeeze removes singleton dimensions: squeeze(zeros(1, 3, 1, 5)) produces a 3×5 matrix.
Reshaping and permuting
A = 1:12;
B = reshape(A, [3, 4])
% 3×4:
% 1 4 7 10
% 2 5 8 11
% 3 6 9 12
reshape is cheap (it changes the size metadata but does not copy the elements) and obeys column-major order: the elements of A fill the first column of B first.
permute(A, [2 1 3]) swaps the first two dimensions of a 3-d array; transpose (A.') and ctranspose (A') are the 2-d cases. flip(A, dim), fliplr(A), flipud(A), and rot90(A) perform reflections and 90-degree rotations.
A = magic(3);
A.' % plain transpose
flip(A, 1) % flip rows
rot90(A) % rotate 90° counter-clockwise
Concatenation
The bracket form concatenates arrays of compatible shape; the operator [] is overloaded for both construction and concatenation. The functions horzcat, vertcat, and cat(dim, A, B, ...) are the programmatic equivalents:
A = [1 2; 3 4];
B = [5 6; 7 8];
[A, B] % 2×4 horizontal
[A; B] % 4×2 vertical
cat(3, A, B) % 2×2×2 along third dimension
Empty arrays act as the concatenation identity: [A, []] is A.
N-d arrays
A 3-d array is constructed with cat, reshape, or by indexed assignment:
A = zeros(3, 3, 2);
A(:, :, 1) = magic(3);
A(:, :, 2) = magic(3) * 10;
The third dimension is conventionally called a page. The standard library’s reduction functions — sum, mean, max — accept a dim argument that collapses along the chosen dimension:
sum(A, 1) % collapse rows; result is 1×3×2
sum(A, 'all') % scalar, sum of all elements
The pagemtimes, pageinv, pagetranspose family (R2020b and later) perform per-page linear-algebra on a 3-d array of matrices, a frequent need in batched applications.
Growth, preallocation, and the JIT
Growing an array by indexed assignment is expensive: each growth allocates a new array and copies the old contents. The MATLAB editor warns “The variable appears to change size on every loop iteration” — a real warning, not a stylistic one. The remedy is to preallocate:
% Bad: grows on each iteration
x = [];
for k = 1:1e6
x(k) = k^2;
end
% Good: preallocate
x = zeros(1, 1e6);
for k = 1:1e6
x(k) = k^2;
end
% Better: vectorise
x = (1:1e6) .^ 2;
The third form is the idiomatic MATLAB: it eliminates the loop entirely and yields the cleanest, fastest code. The JIT will compile the second form efficiently, but the vectorised expression is shorter, more readable, and frequently faster.
Sparse arrays
A sparse matrix is a matrix that stores only its non-zero entries, indexed by row and column. The class is sparse; construction is by sparse(i, j, v, m, n):
S = sparse([1 2 3], [1 2 3], [10 20 30], 3, 3);
% 3×3 sparse: diagonal of [10 20 30]
The standard library accepts sparse matrices through most linear-algebra and arithmetic operations; the storage saving and the operation-count saving are enormous for matrices with a small fraction of non-zero entries. The function nnz(S) returns the count of non-zeros; full(S) converts to a dense matrix.
GPU and tall arrays
The gpuArray class (Parallel Computing Toolbox) wraps an array on a GPU; the supported operations dispatch to CUDA implementations and return another gpuArray. The tall class wraps an array that is too large to fit in memory and is computed lazily through deferred evaluation:
x = gpuArray(rand(1000)); % on the GPU
y = sin(x) .* cos(x); % executed on the GPU
z = gather(y); % bring back to host memory
T = tall(datastore("logs/*.csv"));
result = gather(mean(T.Latency));
The classes are type-compatible with regular numeric arrays: most user code that operates on double works on gpuArray and tall without modification.
Equality, comparison, and isequal
Element-wise equality returns a logical array of the same shape; isequal(A, B) returns a single logical that compares as a whole and considers shape as well as values. isequal is strict on class: isequal(int32(1), 1) is false because the classes differ; isequaln is isequal with the modification that NaN == NaN counts as equal.
isequal([1 2 3], [1 2 3]) % true
isequal([1 2 3], [1 2 3]') % false (shape differs)
isequal([NaN 2 3], [NaN 2 3]) % false (NaN ~= NaN)
isequaln([NaN 2 3], [NaN 2 3]) % true