Skip to content
Linear Algebra
step 1/5

Reading — step 1 of 5

Learn

~2 min readLinear Algebra, Strings, Plotting

Octave was BORN for linear algebra. Operators and built-ins do what scientists actually need.

Matrix arithmetic

A = [1 2; 3 4];
B = [5 6; 7 8];

A + B           % element-wise
A * B           % matrix multiply: [19 22; 43 50]
A .* B          % element-wise multiply: [5 12; 21 32]
A'              % transpose
A^2             % A * A
A.^2            % element-wise square

The . distinguishes element-wise from matrix ops. * is matrix multiply, .* is Hadamard product. ^ is matrix power, .^ is element-wise.

Solve linear systems

%% Ax = b — solve for x
A = [1 2; 3 4];
b = [5; 11];
x = A \ b      % left-divide — solves Ax = b
               % x = [1; 2]

The \ is Octave's solve operator. Faster and more numerically stable than inv(A) * b.

For xA = b: x = b / A (right-divide).

Matrix decompositions

[Q, R] = qr(A)            %% QR decomposition
[L, U, P] = lu(A)          %% LU
[V, D] = eig(A)            %% eigenvalues + eigenvectors
[U, S, V] = svd(A)         %% SVD

These are wrappers around LAPACK. Production-quality numerics.

Useful matrix functions

zeros(3)                    %% 3x3 zero matrix
ones(2, 5)                  %% 2x5 ones matrix
eye(4)                      %% 4x4 identity
rand(3)                     %% random in [0,1]
randn(3)                    %% normal distribution

det(A)                      %% determinant
trace(A)                    %% sum of diagonal
rank(A)                     %% rank
inv(A)                      %% inverse — but use \ instead
norm(v)                     %% Euclidean norm

diag(A)                     %% diagonal as vector
diag([1, 2, 3])             %% diagonal matrix from vector

Indexing

A(1, :)         %% first row
A(:, 1)         %% first column
A(1:2, 1:2)     %% top-left 2x2 submatrix
A(end, end)     %% bottom-right element
A(:)            %% flatten to column vector

: alone selects all. end is the size in that dimension.

Reshape and concatenation

v = 1:12;
M = reshape(v, 3, 4)                    %% 3x4 matrix

A = [1 2; 3 4];
B = [5 6; 7 8];
horzcat(A, B)       %% same as [A, B]
vertcat(A, B)       %% same as [A; B]

Examples

Linear regression in 2 lines:

X = [ones(rows(data), 1), data(:, 1)];   %% add intercept column
theta = X \ data(:, 2);                  %% least-squares fit

This is what makes Octave/MATLAB pleasant — heavy math is one-liners.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…