Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 45 ยท Practice and Review

MATLAB / Octave Cheat Sheet

A one-page MATLAB and Octave cheat sheet covering syntax, operators, indexing, common functions, plotting and the main Octave differences.

This page packs the course into one place: the syntax, operators and functions you use every day, in compact tables you can scan in seconds. Keep it open while you code, while you work through the practice exercises, or before an interview.

Each section names the lesson that explains the topic in depth. All the code below is real MATLAB or Octave and is read-only here, because neither program runs on this site. Two small Python stand-ins at the end let you try the trickiest ideas (1-based, column-major indexing and a plot) in your browser.

One page, six areas

Syntax Variables, output, help.
Operators Matrix and element-wise.
Indexing Ranges, masks, end.
Plots Lines, bars, surfaces.

Numerics and Octave notes follow below.

1 / 2

Basics

Details: Variables, Output and Help and The Desktop, Command Window and Scripts.

Task Code
Assign (print the result) x = 5
Assign quietly x = 5;
Last unassigned result ans
Comment % comment (Octave also accepts #)
Continue a line ... at the end of the line
Print text disp('hi'), fprintf('%d items\n', n)
Number display format long, format short
Clear screen, variables clc, clear, clear all
List variables who, whos
Help help sum, doc sum, lookfor keyword
Run a script type its name (file name.m on the path)
Constants pi, Inf, NaN, eps, 1i (imaginary unit)

Creating arrays

Details: Everything Is a Matrix and Ranges and Special Matrices.

MATLAB
v = [1 2 3];           % row vector
c = [1; 2; 3];         % column vector
M = [1 2; 3 4];        % 2-by-2 matrix
r = 0:0.5:2;           % 0 0.5 1 1.5 2
n = linspace(0, 1, 5); % 5 evenly spaced points
z = zeros(2, 3);  o = ones(2, 3);  I = eye(3);
R = rand(3);  N = randn(3);  K = randi(10, 2, 4);
D = diag([1 2 3]);     m = magic(4);
[X, Y] = meshgrid(1:3, 1:2);
B = repmat([1 2], 2, 2);
Query Function
Size, number of elements size(A), numel(A), length(A), ndims(A)
Rows or columns size(A, 1), size(A, 2)
Empty test isempty(A)
Class class(A), isa(A, 'double')

Operators

Details: Arithmetic: Matrix vs Element-wise.

Meaning Matrix form Element-wise form
Multiply A * B A .* B
Divide A / B, A \ B A ./ B, A .\ B
Power A ^ 2 A .^ 2
Transpose A' (conjugate) A.' (plain)
Group Operators
Compare == ~= < <= > >= (Octave also !=)
Logical on arrays & | ~ xor(a, b)
Logical on scalars (short circuit) && ||
Precedence, high to low transpose and powers, unary minus and ~, * /, + -, :, comparisons, &, |, &&, ||

Implicit expansion: sizes that differ only where one of them is 1 are stretched automatically, so A - mean(A) subtracts each column mean from its column.

Indexing

Details: Indexing and Slicing, Logical Indexing and find and Reshaping, Joining and Sorting.

MATLAB
A(2, 3)        % row 2, column 3
A(2, :)        % entire row 2
A(:, 1)        % entire column 1
A(end, end)    % last element
A(1:2, [1 3])  % rows 1-2, columns 1 and 3
A(5)           % linear index (counts down the columns)
A(:)           % all elements as one column
A(A > 5)       % elements satisfying a condition
A(2, :) = [];  % delete row 2
A(end+1, :) = [7 8 9];   % append a row
Task Function
Positions of true values find(mask), [r, c] = find(mask)
Count, any, all nnz(mask), any(mask), all(mask)
Linear to subscripts [r, c] = ind2sub(size(A), k), sub2ind(size(A), r, c)
Reshape reshape(A, 2, []), squeeze, permute
Join [A, B] (side by side), [A; B] (stacked), cat(3, A, B)
Sort and unique sort(v, 'descend'), sortrows(A, 2), unique(v)
Flip and shift flipud, fliplr, circshift(v, 1)

Common math functions

Details: Built-in Math and Statistics and Linear Algebra Essentials.

Area Functions
Reductions (down columns by default) sum, prod, mean, median, std, var, min, max, cumsum, cumprod
Along rows sum(A, 2), max(A, [], 2)
Index of extremum [m, k] = max(v)
Rounding round, floor, ceil, fix, mod(a, b), rem(a, b)
Elementary abs, sqrt, exp, log, log10, sin, cos, atan2
Linear algebra det, inv, rank, trace, norm, eig, svd, lu, qr, chol
Solve Ax = b x = A \ b
Polynomials polyfit(x, y, n), polyval(p, x), roots(p), conv(p, q)
Interpolation interp1(x, y, xi)
Roots and optimization fzero(f, x0), fminsearch(f, x0)
Calculus trapz(x, y), integral(f, a, b), diff(v), gradient(v), ode45(f, tspan, y0)
Random rng(1) to seed, rand, randn, randi
Signals fft, ifft, filter, conv

Types, text and containers

Details: Numeric Types and Precision, Strings and Character Arrays, Cell Arrays, Structures and Tables and Maps.

MATLAB
x = int8(100) + 100;       % 127 (saturates)
y = uint8(3.5);            % 4 (rounds, halves away from zero)
s = 'hello';               % character array, 1-by-5
t = ["a" "b"];             % string array (MATLAB) - Octave differs
upper(s);  strrep(s, 'l', 'L');  strsplit('a,b,c', ',');
num2str(3.14159, 4);  str2double('2.5');  sprintf('%5.2f', pi);
strcmp(a, b);              % compare text; never use == for this

c = {1, 'two', [3 4 5]};   % cell array
c{2}                       % contents ('two');  c(2) is a 1-by-1 cell
cellfun(@numel, c)         % apply a function to every cell

p.name = 'Ada';  p.age = 36;      % struct
fieldnames(p);  isfield(p, 'age');  p.('name');   % dynamic field

Control flow and functions

Details: if, switch and Loops, Scripts and Functions and Anonymous Functions and Function Handles.

MATLAB
if x > 0
    disp('positive')
elseif x == 0
    disp('zero')
else
    disp('negative')
end

switch lower(cmd)
    case {'start', 'go'}
        disp('starting')
    otherwise
        disp('unknown')
end

for k = 1:10, ...   end       % also: for col = A iterates over columns
while cond, ...     end       % use break and continue as usual

function [s, p] = sumprod(a, b)     % file sumprod.m
    s = a + b;
    p = a * b;
end

sq = @(x) x.^2;                     % anonymous function
integral(sq, 0, 1)                  % 1/3
try
    error('myPkg:bad', 'Value %d is bad', 7)
catch err
    disp(err.message)
end

Plotting

Details: 2-D Plots, Bar, Scatter, Histogram and Images and 3-D Plots, Surfaces and Contours.

Goal Code
Line plot plot(x, y, 'r--o') (colour, line style, marker)
Several curves hold on ... hold off
Labels xlabel('x'), ylabel('y'), title('t'), legend('a', 'b')
Limits and grid xlim([0 5]), ylim([0 1]), axis equal, grid on
Panels subplot(2, 1, 1), tiledlayout(2, 1) with nexttile
Bar, scatter, histogram bar(y), scatter(x, y), histogram(v) (older: hist)
Log scales semilogx, semilogy, loglog
Image or matrix imagesc(A), colormap(gray), colorbar
3-D plot3, surf(X, Y, Z), mesh, contour, view(45, 30)
Save exportgraphics(gcf, 'f.png') (MATLAB), print -dpng f.png (both)

Files

Details: Reading and Writing Files.

MATLAB
fid = fopen('out.txt', 'w');  fprintf(fid, '%d\n', 1:3);  fclose(fid);
A = readmatrix('data.csv');        % newer MATLAB; csvread / dlmread elsewhere
save('state.mat', 'A');  load('state.mat');
type out.txt                       % show a text file

Octave differences at a glance

Details: What Are MATLAB and Octave? and MATLAB, Octave and Python Compared.

Topic MATLAB Octave
Comments % % or #
Block ends end end, endif, endfor, endwhile, endfunction
Not equal ~= ~= or !=
Strings 'char' and "string" objects both quote styles make char arrays (double quotes allow escapes)
Increment not available x += 1, x++
Functions in scripts local functions at the end of the file (R2016b and later) define them before use in a script file; also allowed at the prompt
Tables table built in not in core; limited support in packages
Toolboxes add-on products pkg load statistics and other free packages
Printing disp, fprintf same, plus printf
Python 1-based, column-major indexing in a stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A MATLAB-style plot in matplotlib

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in at function shows why a single subscript runs down the columns, and the matplotlib call uses the same short format string idea ('r--o') that MATLAB's plot accepts.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which operator performs element-wise multiplication?

    .* multiplies matching elements. Plain * is matrix multiplication.
  2. 2. What does A(:, 1) return?

    A colon in the row position means all rows, and the second subscript selects column 1.
  3. 3. Which command solves the linear system Ax = b?

    Backslash is the left-division operator that solves the system directly with a factorization.

Summary

  • Arrays are 1-based, include both range ends, and are stored column by column; end, : and logical masks cover most indexing needs.
  • Use dotted operators for element-wise work; \ solves linear systems.
  • Reductions work down columns by default, so pass a dimension to work along rows.
  • Cells use {} for contents, structs use named fields, and text comparisons need strcmp.
  • Most MATLAB code runs in Octave; watch comments, strings, tables and toolbox functions.

Back to the start of the review chapter: Practice Exercises with Solutions.