Introduction: What is MATLAB?
MATLAB (Matrix Laboratory) is a high-performance programming language and environment for technical computing, data analysis, visualization, and algorithm development. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages.
MATLAB is widely used by engineers, scientists, mathematicians, and researchers for numerical analysis, signal processing, image processing, control systems, and more. Its integrated environment combines computation, visualization, and programming in an easy-to-use platform with powerful built-in functions.
Core Concepts and Principles
Basic Principles
- Matrix-based computation: Everything in MATLAB is fundamentally a matrix
- Vectorized operations: Apply operations to entire arrays without explicit loops
- Dynamically typed: Variable types are determined at runtime
- Interactive and scripted execution: Run commands directly or save as scripts
- Object-oriented programming: Create and use classes and objects
- Integrated visualization: Built-in functions for plotting and visualization
MATLAB Working Environment
Component | Description |
---|
Command Window | Interactive terminal to execute commands |
Workspace | Area that stores all variables |
Editor | Interface for writing and editing scripts |
Current Folder | Directory where MATLAB looks for files by default |
Command History | Record of previously executed commands |
Variable Explorer | Tool for inspecting variables in the workspace |
App Gallery | Collection of interactive applications |
Getting Started with MATLAB
Basic Commands and Operations
Command | Description |
---|
help function_name | Display help for specified function |
clc | Clear Command Window |
clear | Remove items from workspace |
clear all | Remove all variables from workspace |
close all | Close all figures |
who | List variables in workspace |
whos | List variables with sizes and types |
exit or quit | Exit MATLAB |
ctrl+c | Interrupt current operation |
format short/long | Control number display format |
diary filename | Save Command Window text to file |
path | Display search path |
addpath | Add directories to search path |
Variables and Data Types
Operation | Syntax | Description |
---|
Assignment | x = 5 | Assign value to variable |
Multiple assignments | [a,b] = deal(1,2) | Assign multiple values |
Array | a = [1 2 3] | Create row vector |
Column vector | a = [1; 2; 3] | Create column vector |
Matrix | A = [1 2; 3 4] | Create 2×2 matrix |
Cell array | C = {1, 'text', [1 2]} | Create heterogeneous container |
Structure | S.name = 'value' | Create field-based structure |
Strings | str = "text" | Create string object |
Character array | str = 'text' | Create character array |
Logical | L = true | Boolean true or false value |
Operators and Special Characters
Arithmetic Operators
Operator | Description | Example |
---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Matrix multiplication | A * B |
.* | Element-wise multiplication | A .* B |
/ | Right division | A / B |
./ | Element-wise right division | A ./ B |
\ | Left division | A \ B |
.\ | Element-wise left division | A .\ B |
^ | Matrix power | A ^ 2 |
.^ | Element-wise power | A .^ 2 |
' | Complex conjugate transpose | A' |
.' | Transpose | A.' |
Relational Operators
Operator | Description | Example |
---|
< | Less than | a < b |
<= | Less than or equal | a <= b |
> | Greater than | a > b |
>= | Greater than or equal | a >= b |
== | Equal to | a == b |
~= | Not equal to | a ~= b |
Logical Operators
Operator | Description | Example |
---|
& | Logical AND | a & b |
` | ` | Logical OR |
~ | Logical NOT | ~a |
&& | Short-circuit AND | a && b |
` | | ` |
xor | Exclusive OR | xor(a, b) |
Special Characters
Character | Description | Example |
---|
[] | Array constructor | a = [1 2 3] |
() | Function argument, indexing | sin(x), A(1,2) |
{} | Cell array constructor, indexing | c = {1, 'text'}, c{1} |
. | Structure field access, decimal point | s.field, 3.14 |
, | Separator for function arguments | max(x, y) |
; | Suppress output, row separator | x = 5; |
% | Comment | % This is a comment |
... | Line continuation | a = 1 + 2 + ... |
: | Range operator, all elements | 1:5, A(:, 1) |
@ | Function handle | @sin |
Matrix Creation and Manipulation
Creating Matrices
Function | Description | Example |
---|
zeros | Matrix of zeros | zeros(3, 4) |
ones | Matrix of ones | ones(2) |
eye | Identity matrix | eye(3) |
rand | Uniform random numbers | rand(3, 4) |
randn | Normal random numbers | randn(3, 4) |
magic | Magic square | magic(3) |
linspace | Linearly spaced vector | linspace(0, 1, 5) |
logspace | Logarithmically spaced vector | logspace(0, 2, 5) |
meshgrid | 2D and 3D grids | [X, Y] = meshgrid(1:3, 1:4) |
diag | Diagonal matrix or diagonal of matrix | diag([1 2 3]) |
blkdiag | Block diagonal matrix | blkdiag(A, B) |
repmat | Replicate and tile matrix | repmat(A, 2, 3) |
cat | Concatenate arrays | cat(dim, A, B, ...) |
Matrix Manipulation
Function | Description | Example |
---|
size | Array dimensions | size(A) |
length | Length of vector | length(x) |
ndims | Number of dimensions | ndims(A) |
numel | Number of elements | numel(A) |
reshape | Reshape array | reshape(A, 2, 6) |
squeeze | Remove singleton dimensions | squeeze(A) |
permute | Permute array dimensions | permute(A, [2 1 3]) |
ipermute | Inverse permute | ipermute(A, [2 1 3]) |
flip | Flip array | flip(A) |
fliplr | Flip array left to right | fliplr(A) |
flipud | Flip array up to down | flipud(A) |
rot90 | Rotate array 90 degrees | rot90(A) |
circshift | Shift array circularly | circshift(A, [1 -2]) |
shiftdim | Shift dimensions | shiftdim(A, 1) |
transpose | Non-conjugate transpose | transpose(A) |
ctranspose | Complex conjugate transpose | ctranspose(A) |
Matrix Indexing and Slicing
Operation | Description | Example |
---|
Linear indexing | Access by single index | A(5) |
Subscripted indexing | Access by row, column | A(2, 3) |
Range indexing | Access range of elements | A(1:3, 2:4) |
Logical indexing | Access by logical array | A(A > 5) |
Colon operator | All elements in dimension | A(:, 2) |
End reference | Last index | A(end, :) |
Cell content | Access cell contents | C{1} |
Structure field | Access structure field | S.fieldname |
Dynamic field names | Computed field access | S.(variable) |
Multiple outputs | Get multiple elements | [a, b, c] = deal(C{:}) |
Control Flow and Programming Constructs
Conditional Statements
% if-elseif-else statement
if condition1
statements1
elseif condition2
statements2
else
statements3
end
% switch statement
switch expression
case value1
statements1
case {value2, value3}
statements2
otherwise
statements3
end
% try-catch statement
try
statements
catch ME
error_handling_statements
end
Loops
% for loop
for i = vector
statements
end
% while loop
while condition
statements
end
% break statement - exit loop
for i = 1:10
if i > 5
break
end
end
% continue statement - skip to next iteration
for i = 1:10
if i == 5
continue
end
end
Functions
% Basic function
function [output1, output2] = functionName(input1, input2)
% function body
output1 = input1 + input2;
output2 = input1 * input2;
end
% Anonymous function
f = @(x) x^2 + 2*x + 1;
% Nested function
function parentFunc()
x = 5;
function nestedFunc()
% Can access x from parent scope
disp(x);
end
nestedFunc();
end
% Function handles
fh = @sin;
result = fh(pi/2);
Data Import/Export and File I/O
File Operations
Function | Description | Example |
---|
pwd | Current directory | pwd |
cd | Change directory | cd 'path' |
dir or ls | List directory contents | dir |
mkdir | Create directory | mkdir('newdir') |
rmdir | Remove directory | rmdir('dir') |
delete | Delete file | delete('file.txt') |
copyfile | Copy file | copyfile('source', 'dest') |
movefile | Move file | movefile('source', 'dest') |
exist | Check if file or variable exists | exist('file.m', 'file') |
which | Full path to function | which('sin') |
what | Functions in directory | what |
type | Display contents of file | type('file.m') |
fileparts | Parse filename parts | [p, n, e] = fileparts('file.txt') |
fullfile | Build full file name | fullfile('dir', 'file.txt') |
Data Import/Export
Function | Description | Example |
---|
load | Load variables from file | load('data.mat') |
save | Save variables to file | save('data.mat', 'x', 'y') |
readtable | Read tabular data | T = readtable('data.csv') |
writetable | Write tabular data | writetable(T, 'data.csv') |
readmatrix | Read matrix from file | A = readmatrix('data.txt') |
writematrix | Write matrix to file | writematrix(A, 'data.txt') |
readcell | Read cell array from file | C = readcell('data.xlsx') |
writecell | Write cell array to file | writecell(C, 'data.xlsx') |
csvread | Read CSV file (legacy) | csvread('data.csv') |
csvwrite | Write CSV file (legacy) | csvwrite('data.csv', A) |
xlsread | Read Excel file (legacy) | [num, txt] = xlsread('data.xlsx') |
xlswrite | Write Excel file (legacy) | xlswrite('data.xlsx', A) |
importdata | Import data from file | data = importdata('file.dat') |
audioread | Read audio file | [y, Fs] = audioread('audio.wav') |
audiowrite | Write audio file | audiowrite('audio.wav', y, Fs) |
imread | Read image | img = imread('image.jpg') |
imwrite | Write image | imwrite(img, 'image.png') |
Text File I/O
% Reading text file
fid = fopen('file.txt', 'r');
if fid ~= -1
data = textscan(fid, '%f %s');
fclose(fid);
end
% Writing text file
fid = fopen('file.txt', 'w');
if fid ~= -1
fprintf(fid, 'Value: %f\n', 3.14);
fclose(fid);
end
Data Analysis and Statistics
Basic Statistics
Function | Description | Example |
---|
min | Minimum value | min(A) |
max | Maximum value | max(A) |
mean | Average | mean(A) |
median | Median value | median(A) |
mode | Most frequent value | mode(A) |
std | Standard deviation | std(A) |
var | Variance | var(A) |
cov | Covariance | cov(A, B) |
corrcoef | Correlation coefficients | corrcoef(A, B) |
sort | Sort array | sort(A) |
sortrows | Sort rows of matrix | sortrows(A, 2) |
histcounts | Histogram bin counts | histcounts(A) |
prctile | Percentiles | prctile(A, [25 50 75]) |
quantile | Quantiles | quantile(A, [0.25 0.5 0.75]) |
iqr | Interquartile range | iqr(A) |
range | Range of values | range(A) |
cumsum | Cumulative sum | cumsum(A) |
cumprod | Cumulative product | cumprod(A) |
diff | Differences | diff(A) |
gradient | Numerical gradient | gradient(A) |
Linear Algebra
Function | Description | Example |
---|
inv | Matrix inverse | inv(A) |
pinv | Pseudoinverse | pinv(A) |
det | Determinant | det(A) |
trace | Sum of diagonal elements | trace(A) |
norm | Matrix or vector norm | norm(A) |
rank | Rank of matrix | rank(A) |
null | Null space | null(A) |
orth | Orthonormal basis | orth(A) |
eig | Eigenvalues and eigenvectors | [V, D] = eig(A) |
svd | Singular value decomposition | [U, S, V] = svd(A) |
chol | Cholesky factorization | R = chol(A) |
lu | LU factorization | [L, U, P] = lu(A) |
qr | QR factorization | [Q, R] = qr(A) |
dot | Dot product | dot(a, b) |
cross | Cross product | cross(a, b) |
kron | Kronecker tensor product | kron(A, B) |
expm | Matrix exponential | expm(A) |
logm | Matrix logarithm | logm(A) |
sqrtm | Matrix square root | sqrtm(A) |
rref | Reduced row echelon form | rref(A) |
linsolve | Solve linear system | linsolve(A, b) |
Curve Fitting and Interpolation
Function | Description | Example |
---|
polyfit | Polynomial curve fitting | p = polyfit(x, y, n) |
polyval | Evaluate polynomial | y_fit = polyval(p, x) |
interp1 | 1-D interpolation | yi = interp1(x, y, xi) |
interp2 | 2-D interpolation | zi = interp2(x, y, z, xi, yi) |
spline | Cubic spline interpolation | yi = spline(x, y, xi) |
pchip | Piecewise cubic Hermite interpolation | yi = pchip(x, y, xi) |
fit | Fit curve or surface to data | f = fit(x, y, 'poly2') |
lsqcurvefit | Solve nonlinear curve-fitting | lsqcurvefit(@func, x0, xdata, ydata) |
Visualization and Plotting
2D Plotting
Function | Description | Example |
---|
plot | 2D line plot | plot(x, y) |
scatter | Scatter plot | scatter(x, y) |
bar | Bar graph | bar(x, y) |
barh | Horizontal bar graph | barh(x, y) |
histogram | Histogram plot | histogram(x) |
stairs | Stairstep plot | stairs(x, y) |
stem | Stem plot | stem(x, y) |
area | Area plot | area(x, y) |
pie | Pie chart | pie(x) |
polar | Polar coordinate plot | polar(theta, rho) |
loglog | Log-log scale plot | loglog(x, y) |
semilogx | Semilog scale (x-axis) | semilogx(x, y) |
semilogy | Semilog scale (y-axis) | semilogy(x, y) |
errorbar | Error bar plot | errorbar(x, y, err) |
boxplot | Box plot | boxplot(data) |
plotmatrix | Scatter plot matrix | plotmatrix(X) |
contour | Contour plot | contour(X, Y, Z) |
contourf | Filled contour plot | contourf(X, Y, Z) |
quiver | Vector plot | quiver(X, Y, U, V) |
compass | Compass plot | compass(u, v) |
feather | Feather plot | feather(u, v) |
fplot | Function plot | fplot(@sin, [0, 2*pi]) |
3D Plotting
Function | Description | Example |
---|
plot3 | 3D line plot | plot3(x, y, z) |
scatter3 | 3D scatter plot | scatter3(x, y, z) |
surf | 3D surface plot | surf(X, Y, Z) |
surfc | Surface with contour | surfc(X, Y, Z) |
mesh | 3D mesh plot | mesh(X, Y, Z) |
meshc | Mesh with contour | meshc(X, Y, Z) |
contour3 | 3D contour plot | contour3(X, Y, Z) |
isosurface | Isosurface from 3D data | isosurface(X, Y, Z, V) |
slice | Volumetric slice plot | slice(X, Y, Z, V, xi, yi, zi) |
streamline | 3D streamlines | streamline(X, Y, Z, U, V, W, startx, starty, startz) |
coneplot | 3D velocity vectors | coneplot(X, Y, Z, U, V, W, cx, cy, cz) |
Plot Customization
Function | Description | Example |
---|
figure | Create figure window | figure |
subplot | Create subplot | subplot(2, 2, 1) |
title | Add title | title('Plot Title') |
xlabel | Add x-axis label | xlabel('X Label') |
ylabel | Add y-axis label | ylabel('Y Label') |
zlabel | Add z-axis label | zlabel('Z Label') |
legend | Add legend | legend('Data 1', 'Data 2') |
grid | Add grid lines | grid on |
box | Toggle plot box | box off |
axis | Control axis scaling and appearance | axis equal |
xlim | Set x-axis limits | xlim([0, 10]) |
ylim | Set y-axis limits | ylim([-1, 1]) |
zlim | Set z-axis limits | zlim([0, 5]) |
colormap | Set colormap | colormap(jet) |
colorbar | Add color bar | colorbar |
caxis | Set color axis limits | caxis([0, 1]) |
view | Set viewpoint | view(3) |
shading | Control surface shading | shading flat |
lighting | Control lighting | lighting gouraud |
text | Add text to plot | text(x, y, 'Text') |
annotation | Add annotation | annotation('arrow', [x1 x2], [y1 y2]) |
hold | Hold current plot | hold on |
Common Challenges and Solutions
Memory Management
Challenge | Solution |
---|
Out of memory | Use sparse matrices for large, sparse data |
| Process data in chunks |
| Clear unused variables with clear |
| Use single precision with single() |
Large file processing | Use memory-mapped files with memmapfile |
| Use datastore for big data |
Slow loops | Vectorize operations when possible |
| Preallocate arrays before loops |
| Use arrayfun or cellfun for element-wise operations |
Debugging
Function | Description | Example |
---|
dbstop | Set breakpoint | dbstop in file at line |
dbclear | Clear breakpoint | dbclear all |
dbcont | Continue execution | dbcont |
dbstep | Execute one line | dbstep |
dbquit | Quit debug mode | dbquit |
try/catch | Error handling | try ... catch ME ... end |
warning | Display warning | warning('Warning message') |
error | Display error | error('Error message') |
assert | Verify condition | assert(condition, 'message') |
profile | Profile code execution | profile on/off/viewer |
Common Errors and Solutions
Error | Possible Solution |
---|
Indexing error | Check array dimensions with size() |
| Use end for last element |
| Ensure indices are valid |
Matrix dimensions | Use size , ndims , length to check dimensions |
| Use reshape , squeeze , or permute to adjust |
| Use .' for transpose (not ' for complex data) |
Function not found | Ensure function is on path or in current directory |
| Check spelling and case sensitivity |
| Use which to locate function |
Stack overflow | Optimize recursion with base cases |
| Consider iterative approach instead |
Data type issues | Check types with class() |
| Use conversion functions like double() , int32() , etc. |
| Use isa() to verify type |
Best Practices and Tips
Code Optimization
- Vectorize operations instead of using loops when possible
- Preallocate arrays before filling them in loops
- Use built-in functions when available (they’re typically optimized)
- Avoid growing arrays inside loops (use preallocation)
- Use
tic/toc
or timeit
to profile code segments - Consider using the Parallel Computing Toolbox for parallel operations
- Use sparse matrices for large, sparse data
- Access matrices in column-major order for better performance
- Use
bsxfun
for binary singleton expansion (pre-R2016b) - Use logical indexing instead of
find
when appropriate
Coding Style
- Use meaningful variable names
- Comment code thoroughly, especially complex sections
- Create modular, reusable functions
- Include error checking in functions
- Document function inputs and outputs with help comments
- Follow MATLAB’s naming conventions (camelCase for variables, etc.)
- Create scripts that can run from start to finish without errors
- Use consistent indentation and spacing
- Avoid “magic numbers” – use named constants instead
- Use cell mode (
%%
) to divide scripts into logical sections
Resources for Further Learning
Official Documentation
Books
- “MATLAB: A Practical Introduction to Programming and Problem Solving” by Stormy Attaway
- “MATLAB for Engineers” by Holly Moore
- “Numerical Computing with MATLAB” by Cleve Moler
Online Resources