MATLAB Cheatsheet

Syntax, matrices, plotting, functions & common operations

Language
Contents
📝

Basics

% Variable assignment
x = 10;               % semicolon suppresses output
y = 3.14;
name = 'Alice';
flag = true;

% Display
disp(x)
fprintf('x = %d\n', x)

% Type checking
class(x)               % 'double'
whos                   % list all variables
clear                  % clear workspace
clc                    % clear command window

% Help
help sin               % quick help
doc sin                % full documentation
📦

Matrices

% Create
A = [1 2 3; 4 5 6; 7 8 9];    % 3×3 matrix
v = [1 2 3 4 5];                 % row vector
c = [1; 2; 3];                   % column vector

% Special matrices
zeros(3, 4)        % 3×4 zeros
ones(3, 4)         % 3×4 ones
eye(4)             % 4×4 identity
rand(3, 4)         % 3×4 random [0,1)
randn(3, 4)        % 3×4 normal dist
linspace(0, 1, 5)  % 5 evenly spaced
1:5                 % [1 2 3 4 5]
0:0.5:3            % [0 0.5 1 1.5 2 2.5 3]

% Properties
size(A)      length(v)     numel(A)
🔢

Indexing

% 1-based indexing!
A(1, 2)              % row 1, col 2
A(1, :)              % entire row 1
A(:, 2)              % entire column 2
A(1:2, 1:2)          % submatrix
A(end, :)            % last row
A(:)                  % all elements as column

% Logical indexing
A(A > 5)             % elements > 5
A(A > 3 & A < 7)    % between 3 and 7

Operations

% Matrix arithmetic
A + B    A - B    A * B    A / B
A'                       % transpose
inv(A)                   % inverse
det(A)                   % determinant
A \ b                    % solve Ax=b

% Element-wise (dot operator)
A .* B    A ./ B    A .^ 2

% Statistics
sum(A)    mean(A)    max(A)    min(A)
std(A)    var(A)     median(A)
sort(A)   cumsum(A)

% Math
sqrt(x)   abs(x)   exp(x)   log(x)
sin(x)    cos(x)   floor(x) ceil(x)
📊

Plotting

% Basic plot
x = 0:0.1:10;
y = sin(x);
plot(x, y)
title('Sine Wave')
xlabel('x')
ylabel('sin(x)')
grid on

% Multiple plots
hold on
plot(x, cos(x), 'r--')
legend('sin', 'cos')
hold off

% Other plot types
scatter(x, y)     bar(x, y)
histogram(data)   pie(data)
subplot(2,1,1)   % 2 rows, 1 col, plot 1

% Save figure
saveas(gcf, 'plot.png')
🔀

Control Flow

% If
if x > 0
    disp('positive')
elseif x < 0
    disp('negative')
else
    disp('zero')
end

% For loop
for i = 1:10
    fprintf('%d ', i)
end

% While loop
i = 1;
while i <= 5
    disp(i)
    i = i + 1;
end

% Switch
switch day
    case 'Mon', disp('Monday')
    case 'Tue', disp('Tuesday')
    otherwise, disp('Other')
end

Functions

% Function file (save as myfunc.m)
function result = myfunc(x, y)
    result = x + y;
end

% Multiple outputs
function [mn, mx] = minmax(arr)
    mn = min(arr);
    mx = max(arr);
end

% Anonymous function
f = @(x) x.^2 + 1;
f(3)                 % 10

% Apply to array
arrayfun(@(x) x^2, [1 2 3])
cellfun(@length, {'hi', 'hello'})
💾

I/O

% Load / Save
save('data.mat', 'x', 'y')   % save variables
load('data.mat')              % load variables

% CSV
data = readmatrix('data.csv');
writematrix(data, 'out.csv');

% Table
T = readtable('data.csv');
writetable(T, 'out.csv');

% File I/O
fid = fopen('file.txt', 'r');
line = fgetl(fid);
fclose(fid);