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.
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]B = [1; 2; 3]C = [1, 2, 3]D = zeros(3, 4)E = ones(2, 3)F = eye(3)G = rand(3, 3)H = linspace(0, 10, 100)Matrix Operations 11
A'inv(A)det(A)rank(A)trace(A)eig(A)svd(A)A * BA .* BA / BA \ BData Visualization 16
plot(x, y)scatter(x, y)bar(x, y)hist(data)pie(data)surf(X, Y, Z)mesh(X, Y, Z)contour(X, Y, Z)title("Chart Title")xlabel("X Axis")ylabel("Y Axis")legend("Curve 1", "Curve 2")grid onhold onhold offsubplot(2, 2, 1)Data Processing 12
mean(A)median(A)std(A)var(A)max(A)min(A)sum(A)cumsum(A)diff(A)sort(A)unique(A)find(A > 5)File I/O 10
load("data.mat")save("data.mat", "var")data = csvread("file.csv")csvwrite("file.csv", data)data = xlsread("file.xlsx")xlswrite("file.xlsx", data)fid = fopen("file.txt", "r")fclose(fid)fscanf(fid, "%f", [1, inf])fprintf(fid, "%f\n", data)Programming Basics 10
for i = 1:10 ... endwhile condition ... endif condition ... elseif ... else ... endswitch expr case val1 ... otherwise ... endfunction [out] = func(in) ... end% comment%{ block comment %}disp("message")fprintf("format %d\n", var)input("Prompt: ")Linear Algebra 9
A * x = bx = A \ b[L, U, P] = lu(A)[Q, R] = qr(A)[U, S, V] = svd(A)norm(A)cond(A)null(A)orth(A)Signal Processing 7
fft(x)ifft(X)conv(x, y)xcorr(x, y)filter(b, a, x)spectrogram(x)psd(x)Parameter matrix
| Parameter | Effect | Example |
|---|---|---|
A = [1 2 3; 4 5 6; 7 8 9] | Create a 3x3 matrix with semicolons separating rows | A = [1 2 3; 4 5 6; 7 8 9] |
zeros(m,n) | Create an m×n zero matrix, a preallocation base | D = zeros(3, 4) |
ones(m,n) | Create an m×n all-ones matrix | E = ones(2, 3) |
eye(n) | Create an n×n identity matrix | F = eye(3) |
rand(m,n) | Create an m×n random matrix | G = rand(3, 3) |
linspace(a,b,n) | Generate n evenly spaced points from a to b | H = linspace(0, 10, 100) |
A' / A.' | Conjugate transpose / plain transpose (use .' for complex data) | C = A'; |
x = A \ b | Left division to solve a linear system, numerically more stable than inv(A)*b | x = A \ b |
inv(A) | Explicit inversion, requiring a square matrix with nonzero det | B = inv(A) |
det(A) / rank(A) | Determinant and rank, to judge singularity | det(A) |
cond(A) | Condition number, measuring solution stability | cond(A) |
A .* B | Element-wise multiplication; shapes must match | C = 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 variance | s = std(A) |
sort(A) / unique(A) | Sorting and deduplication | idx = find(A > 5) |
subplot(2,2,k) | Position the k-th plot in a 2x2 subplot grid | subplot(2, 2, 1) |
hold on / hold off | Hold the figure for continued drawing / release the hold | hold on; plot(x, y); hold off |
fft(x) / ifft(X) | Fast Fourier transform and its inverse | X = fft(x) |
filter(b, a, x) | Digital filtering by numerator/denominator coefficients | y = filter(b, a, x) |
save("f.mat","var") | Write variables to a MAT file | save("data.mat", "var") |
csvread / csvwrite | Read / write a CSV file | csvwrite("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
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.
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).
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.
4Overlay multiple curves
hold on; plot(x, y1); plot(x, y2); legend("Curve 1", "Curve 2"); hold offAfter 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.
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.
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 =
2Solve linear systems with left division instead of inv
A = [2 1; 1 3]
b = [5; 10]
x = A \ bLeft 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
3Pick 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 onplot(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 3Common 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