MATLAB Cheatsheet - MATLAB Commands & Matrix Operations Reference

This reference is for engineers and scientists who think in matrices rather than element loops. It covers building matrices and vectors, in-place operations like transpose and eigenvalue decomposition, statistical summaries, plotting curves and surfaces, file read/write, and FFT-based signal analysis. Unlike numpy the commands here feel native to the language, so you can type them directly in the Command Window and inspect each result. After reading you should be able to assemble a matrix, transpose/invert/decompose it, turn a vector into a plot, and save the intermediate result with save/load.

Languages·83 commands·Last updated 2026-07-21
matlabScientific ComputingMatrices

Typical Use Case

For engineers and researchers doing numerical work, prototyping algorithms or teaching: the hard part of MATLAB is not the syntax but the overloads. Three of them cause most wrong answers — * is matrix multiplication while .* is element-wise, A\b solves the linear system while inv(A)*b is numerically worse, and mean(A) averages down the first dimension (columns) unless you pass 2. Also covered: A-prime for conjugate transpose versus the plain transpose operator, which almost everyone gets wrong once. The daily loop runs from linspace to matrices, statistics, plotting with hold on and subplot, and file I/O with csvread and fopen.

Matrix Creation 8

A = [1 2 3; 4 5 6; 7 8 9]
Create a 3x3 matrix
B = [1; 2; 3]
Create a column vector
C = [1, 2, 3]
Create a row vector
D = zeros(3, 4)
Create a 3x4 zero matrix
E = ones(2, 3)
Create a 2x3 ones matrix
F = eye(3)
Create a 3x3 identity matrix
G = rand(3, 3)
Create a 3x3 random matrix
H = linspace(0, 10, 100)
100 evenly spaced points from 0 to 10

Matrix Operations 11

A'
Matrix transpose
inv(A)
Matrix inverse
det(A)
Matrix determinant
rank(A)
Matrix rank
trace(A)
Matrix trace (sum of diagonal)
eig(A)
Eigenvalues and eigenvectors
svd(A)
Singular value decomposition
A * B
Matrix multiplication
A .* B
Element-wise multiplication
A / B
Right division (A * inv(B))
A \ B
Left division (inv(A) * B)

Data Visualization 16

plot(x, y)
Plot a 2D curve
scatter(x, y)
Scatter plot
bar(x, y)
Bar chart
hist(data)
Histogram
pie(data)
Pie chart
surf(X, Y, Z)
3D surface plot
mesh(X, Y, Z)
3D mesh plot
contour(X, Y, Z)
Contour plot
title("Chart Title")
Set the chart title
xlabel("X Axis")
Set the X-axis label
ylabel("Y Axis")
Set the Y-axis label
legend("Curve 1", "Curve 2")
Add a legend
grid on
Show grid
hold on
Hold the current figure and keep drawing
hold off
Release the figure hold
subplot(2, 2, 1)
Create the 1st of a 2x2 subplot grid

Data Processing 12

mean(A)
Compute the mean
median(A)
Compute the median
std(A)
Compute the std deviation
var(A)
Compute the variance
max(A)
Compute the max
min(A)
Compute the min
sum(A)
Compute the sum
cumsum(A)
Compute the cumulative sum
diff(A)
Compute differences
sort(A)
Sort
unique(A)
Unique values
find(A > 5)
Find indices meeting a condition

File I/O 10

load("data.mat")
Load a MAT file
save("data.mat", "var")
Save variables to a MAT file
data = csvread("file.csv")
Read a CSV file
csvwrite("file.csv", data)
Write a CSV file
data = xlsread("file.xlsx")
Read an Excel file
xlswrite("file.xlsx", data)
Write an Excel file
fid = fopen("file.txt", "r")
Open a text file
fclose(fid)
Close a file
fscanf(fid, "%f", [1, inf])
Read file contents
fprintf(fid, "%f\n", data)
Write file contents

Programming Basics 10

for i = 1:10 ... end
for loop
while condition ... end
while loop
if condition ... elseif ... else ... end
Conditional (if/elseif/else)
switch expr case val1 ... otherwise ... end
switch statement
function [out] = func(in) ... end
Define a function
% comment
Single-line comment
%{ block comment %}
Block comment
disp("message")
Display a message
fprintf("format %d\n", var)
Formatted output
input("Prompt: ")
User input

Linear Algebra 9

A * x = b
Solve a linear system
x = A \ b
Solve via left division
[L, U, P] = lu(A)
LU decomposition
[Q, R] = qr(A)
QR decomposition
[U, S, V] = svd(A)
SVD
norm(A)
Matrix norm
cond(A)
Condition number
null(A)
Null space basis
orth(A)
Orthogonal basis

Signal Processing 7

fft(x)
Fast Fourier transform
ifft(X)
Inverse FFT
conv(x, y)
Convolution
xcorr(x, y)
Cross-correlation
filter(b, a, x)
Digital filtering
spectrogram(x)
Spectrogram
psd(x)
Power spectral density

Parameter matrix

ParameterEffectExample
A = [1 2 3; 4 5 6; 7 8 9]Create a 3x3 matrix with semicolons separating rowsA = [1 2 3; 4 5 6; 7 8 9]
zeros(m,n)Create an m×n zero matrix, a preallocation baseD = zeros(3, 4)
ones(m,n)Create an m×n all-ones matrixE = ones(2, 3)
eye(n)Create an n×n identity matrixF = eye(3)
rand(m,n)Create an m×n random matrixG = rand(3, 3)
linspace(a,b,n)Generate n evenly spaced points from a to bH = linspace(0, 10, 100)
A' / A.'Conjugate transpose / plain transpose (use .' for complex data)C = A';
x = A \ bLeft division to solve a linear system, numerically more stable than inv(A)*bx = A \ b
inv(A)Explicit inversion, requiring a square matrix with nonzero detB = inv(A)
det(A) / rank(A)Determinant and rank, to judge singularitydet(A)
cond(A)Condition number, measuring solution stabilitycond(A)
A .* BElement-wise multiplication; shapes must matchC = A .* B
mean(A) / mean(A,2)Mean along the first dimension (column-wise) / along the second (row-wise)m = mean(A, 2)
std(A) / var(A)Standard deviation and variances = std(A)
sort(A) / unique(A)Sorting and deduplicationidx = find(A > 5)
subplot(2,2,k)Position the k-th plot in a 2x2 subplot gridsubplot(2, 2, 1)
hold on / hold offHold the figure for continued drawing / release the holdhold on; plot(x, y); hold off
fft(x) / ifft(X)Fast Fourier transform and its inverseX = fft(x)
filter(b, a, x)Digital filtering by numerator/denominator coefficientsy = filter(b, a, x)
save("f.mat","var")Write variables to a MAT filesave("data.mat", "var")
csvread / csvwriteRead / write a CSV filecsvwrite("file.csv", data)

Common pitfalls

SymptomMultiplying two matrices of the same shape produces a 9x9 result or an outright error, and the elements do not line up

CauseIt used matrix multiplication * instead of element-wise .*; * expands via row-column inner products and requires A(m×k) times B(k×n).

FixFor element-wise operations use A .* B, B ./ B, A .^ 2; use * only for linear-algebra multiplication.

SymptomAfter transposing complex data the values look wrong (the imaginary part sign flips) and do not match hand calculations

CauseA' is the conjugate transpose, which also conjugates the imaginary part; it is the wrong choice when you want a plain transpose.

FixFor a complex matrix transpose only (no conjugation) write A.', for example C = A.'.

SymptomSolving the equations gives huge values or a screenful of NaN/Inf, and changing the data makes it completely wrong

CauseCalling inv(A) explicitly and then multiplying by b introduces two inversions, amplifying numerical error; and det itself is tiny when the matrix is near singular.

FixSwitch to left division x = A \ b, and first use det(A), rank(A), cond(A) to judge whether the matrix is ill-conditioned.

SymptomAsking for row-wise statistics returns column-wise results, with a row count different from expected

Causemean(A), sum(A), std(A) default to the first dimension (dim=1), which for a matrix aggregates column by column.

FixFor row-wise, write mean(A, 2), std(A, 2), sum(A, 2) explicitly.

SymptomCalling plot twice in a row, the second curve covers the first and only one line remains in the figure

Causeplot clears the current axes and redraws each time, unless the figure is explicitly held.

FixAdd hold on before the first plot, and hold off to release after all plots are done.

SymptomDefining a function and calling it in a script reports "undefined function" or file not found

CauseA function must share the file name: writing function [out] = myfunc(in) requires saving it as myfunc.m, and that directory must be on the search path.

FixSave the function separately as myfunc.m next to the script (or add its path with addpath), then call myfunc(...).

SymptomAfter load("data.mat") there are no variables in the workspace, or it reports the file does not exist

Causeload uses MAT format by default and looks relative to the current working directory; a relative path is not resolved against the script directory.

FixUse an absolute path or change directory first: load("D:/data/data.mat"); if unsure of the variable names, inspect what was loaded at the command line.

Troubleshooting

  1. 1Confirm whether the matrix is invertible and whether it is ill-conditioned

    det(A); rank(A); cond(A)

    A det of 0 or a rank clearly below the order means the matrix is singular and cannot be inverted; a very large cond (e.g. on the order of 1e10) means the solution is extremely sensitive to perturbations, so check the units of the data or switch to a least-squares approach instead of direct inversion.

  2. 2Distinguish matrix multiplication from element-wise multiplication

    size(A); size(B); C = A .* B; D = A * B;

    First read the size output to confirm both matrix shapes; .* yields the same shape as the inputs, while * changes the result size by the inner-product rule. If .* reports a dimension mismatch, the two operands have different shapes and must be aligned via ones/zeros or reshape; a common scripting practice is to preallocate with zeros(m,n).

  3. 3Print both conventions when the statistic direction is uncertain

    colMean = mean(A); rowMean = mean(A, 2); size(colMean), size(rowMean)

    For a 3x4 matrix, mean(A) returns 1x4 (one mean per column) and mean(A,2) returns 3x1 (one mean per row). Comparing their sizes immediately tells you which is the dimension you want.

  4. 4Overlay multiple curves

    hold on; plot(x, y1); plot(x, y2); legend("Curve 1", "Curve 2"); hold off

    After hold on, each plot reuses the same axes so both curves are visible at once; legend must match the drawing order or the legend will not line up with the lines. Ending with hold off restores normal redraw behavior for later plots.

  5. 5Lay out and position multiple subplots

    subplot(2, 2, 1); plot(x, y1); subplot(2, 2, 2); scatter(x, y2)

    subplot(2,2,k) switches the current axes to the k-th cell of a 2x2 grid; calling it repeatedly fills all four cells. Forgetting subplot makes the later plot overwrite the earlier one.

  6. 6Read and write CSV and text files

    data = csvread("file.csv"); csvwrite("out.csv", data); fid = fopen("log.txt","w"); fprintf(fid, "%f\n", data); fclose(fid)

    csvread/csvwrite suit pure numeric tables; when a header or non-numeric content is needed, open a text stream with fopen, write formatted output with fprintf, and close the handle with fclose. Forgetting fclose means the trailing data never lands on disk.

Command Examples

det and rank immediately expose a singular matrix

A = [1 2 3; 4 5 6; 7 8 9] det(A) rank(A)

In this 1-to-9 matrix the third row is the sum of the first two, so the determinant must be 0 and the rank is only 2. Checking det and rank before attempting an inverse tells you immediately whether the matrix is usable.

Output

ans =
     0
ans =
     2

Solve linear systems with left division instead of inv

A = [2 1; 1 3] b = [5; 10] x = A \ b

Left division is numerically safer than x = inv(A)*b because it never materialises a huge inverse just to multiply it back. Writing inv(A) and multiplying back is a known anti-pattern that visibly loses precision on ill-conditioned matrices.

Output

x =
     1
     3

Pick the decomposition that matches the problem

A = [4 1; 1 3] [L, U, P] = lu(A) [Q, R] = qr(A) [U, S, V] = svd(A)

LU suits solving systems and computing determinants, QR suits least squares, and SVD gives the most numerically stable least-squares solution and enables dimensionality reduction. All three run on the same square matrix, but choosing the wrong one costs far more than a coding typo.

Draw multiple labelled curves in one pass

x = linspace(0, 10, 100) plot(x, sin(x), x, cos(x)) title("Sine and Cosine") legend("sin", "cos") xlabel("X axis") ylabel("Y axis") grid on

plot(x, y1, x, y2) draws both curves in one call, and title / legend / xlabel / grid then layer onto the current figure. Omitting hold on means each subsequent plotting command wipes the previous figure.

Output

ans =
  Columns 1 through 2

    0    1.0000

Select elements by condition instead of nested loops

A = [1 2 3; 4 5 6; 7 8 9] find(A > 5) mean(A) unique([1 1 2 3 3])

find returns linear indices rather than coordinate pairs, so size is needed to turn them back into row/column positions. mean over a matrix averages along the first dimension (down columns); use mean(A, 2) to average across rows.

Output

ans =
     6     7     8     9
ans =
     4     5     6
ans =
     1     2     3

Common Pitfalls

  • A' is the conjugate transpose for complex input; plain transpose is A.' — mixing them up silently changes numeric results.
  • Using end as an index inside a loop (a(end)) and then reading the same variable after the loop makes the index drift, so results are quietly wrong rather than erroring.
  • Statements without a trailing semicolon dump the whole matrix into the command window; a few thousand elements is enough to freeze the editor.
  • for i = 1:10 runs ten times, with i taking 1 through 10 inclusive. A missing element matters when the range feeds a divisor or an index bound.
  • Array indexing starts at 1, not 0: a(0) errors out of range and a(end+1) is how you append. Porting Python or JS logic often breaks here.
  • clear all wipes breakpoints and workspace variables, so variables become undefined and breakpoints stop firing midway through a debugging session.

Tips

  • MATLAB indices start at 1, not 0 (unlike Python/C).
  • Matrix multiply uses *; element-wise uses .* - keep them distinct.
  • plot connects points into a curve; scatter draws individual points.
  • hold on overlays multiple curves on one figure; hold off releases it.
  • load/save default to MAT format; use csvread/csvwrite for CSV.
  • A function file must match the function name, e.g. myfunc.m for function myfunc.
  • Use help to view function docs, e.g. help plot.
  • Use doc to open full documentation, e.g. doc plot.

FAQ

Why should I solve A*x = b with x = A \ b instead of computing the inverse first?

inv(A) materialises the whole inverse and then multiplies it by b, paying two rounds of rounding error on the way, and it demands a square matrix with a non-zero determinant. Backslash hands the job to the internal solver, which is numerically far more stable. If you only need to know whether A is invertible, check det(A) or rank(A) rather than actually calling inv.

My second curve disappears right after the first one — what is wrong?

Each plot call clears the current figure by default, so the previous series is wiped. Call hold on after the first plot so later plot, scatter or bar calls stack on the same axes, then release it with hold off once the figure is complete — otherwise the next script section inherits the state. With several panels, position the axes first via subplot(2, 2, 1) and then hold on inside that panel.

For a complex matrix, should I use A' or A.' for transposition?

A' performs the conjugate transpose and flips the sign of the imaginary part — the mathematically correct choice for complex numbers. A.' performs a plain transpose and leaves the imaginary part alone. On real matrices the two are identical, which is why the difference usually stays hidden, but after an fft the spectrum is complex: using A' there silently flips phase signs. When splitting an fft result into real and imaginary columns, use A.' explicitly.

When does mean(A) on a matrix not give the average I expected?

mean(A) collapses along the first dimension, which for a matrix means column-wise averaging and returns a 1×n row vector. If your rows are the samples and you want one average per row, write mean(A, 2) and you get an m×1 column vector instead. std, sum, max, min, cumsum and diff all follow the same first-dimension rule, so remember the second argument whenever you change direction.

Should I use MAT or CSV files, and what are the trade-offs when exchanging data?

load("data.mat") and save("data.mat", "var") use the MAT format, which preserves matrix type, dimensionality and even complex values — but only MATLAB can read it. csvread("file.csv") and csvwrite("file.csv", data) produce plain text that any tool can parse, at the cost of losing the distinction between a row vector and a 2-D matrix. Keep intermediates in MAT and convert to CSV only when handing data to Python or a human.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us