MATLAB Cheatsheet

What is MATLAB Basic Syntax Variables Matrices Arrays Indexing Operators Functions Control Flow Loops Plotting File I/O Strings Cell Arrays Structures Math Functions Linear Algebra Statistics Signal Processing Optimization Symbolic Math GUI Development Toolboxes Debugging Performance Best Practices

What is MATLAB?

Intro

MATLAB (Matrix Laboratory) is a high-level programming language and numerical computing environment developed by MathWorks. It's widely used for matrix operations, algorithm implementation, and data visualization.

Basic Syntax

Syntax
% This is a comment
x = 5;        % Semicolon suppresses output
y = 10        % No semicolon shows output
disp('Hello'); % Display function

% Multiple statements on one line
a = 1; b = 2; c = 3;

% Line continuation with ...
long_variable_name = 1 + 2 + ...
    3 + 4 + 5;

Variables

Variables
% Variable assignment
x = 10;
myVariable = 3.14;
result = x + myVariable;

% Check variable info
whos x
class(x)
size(x)

% Clear variables
clear x
clear all

Matrices

Matrices
% Create matrices
A = [1 2 3; 4 5 6; 7 8 9];  % 3x3 matrix
B = [1, 2, 3; 4, 5, 6];    % 2x3 matrix

% Special matrices
zeros(3, 4)    % 3x4 matrix of zeros
ones(2, 3)     % 2x3 matrix of ones
eye(3)         % 3x3 identity matrix
rand(2, 2)     % 2x2 random matrix

% Matrix operations
C = A + B;     % Matrix addition
D = A * B;     % Matrix multiplication
E = A .* B;    % Element-wise multiplication

Arrays

Arrays
% Row vector
row_vec = [1 2 3 4 5];

% Column vector
col_vec = [1; 2; 3; 4; 5];

% Using colon operator
vec1 = 1:5;        % [1 2 3 4 5]
vec2 = 1:2:10;     % [1 3 5 7 9]
vec3 = 10:-1:1;    % [10 9 8 7 6 5 4 3 2 1]

% 3D array
array_3d = rand(2, 3, 4);  % 2x3x4 array

% Array functions
length(vec1)       % Length of vector
numel(array_3d)    % Number of elements
ndims(array_3d)    % Number of dimensions

Indexing

Indexing
A = [1 2 3; 4 5 6; 7 8 9];

% Element access
element = A(2, 3);     % Row 2, Column 3
row = A(2, :);         % Entire row 2
col = A(:, 3);         % Entire column 3

% Logical indexing
mask = A > 5;          % Logical matrix
elements = A(mask);    % Elements where A > 5

% Linear indexing
linear_idx = A(5);     % 5th element in linear order

% Submatrix
submatrix = A(1:2, 2:3);  % Rows 1-2, Columns 2-3

Operators

Operators
% Arithmetic operators
a = 5 + 3;     % Addition
b = 10 - 4;    % Subtraction
c = 6 * 7;     % Multiplication
d = 15 / 3;    % Division
e = 2 ^ 3;     % Exponentiation

% Element-wise operations
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A .* B;    % Element-wise multiplication
D = A ./ B;    % Element-wise division

% Logical operators
result1 = (5 > 3) & (2 < 4);  % AND
result2 = (5 > 3) | (2 > 4);  % OR
result3 = ~(5 > 3);           % NOT

Functions

Functions
% Function definition (save as myfunction.m)
function [output1, output2] = myfunction(input1, input2)
    % Function documentation
    % This function does something useful
    
    % Function body
    output1 = input1 + input2;
    output2 = input1 * input2;
end

% Function call
[result1, result2] = myfunction(5, 3);

% Anonymous functions
f = @(x) x^2 + 2*x + 1;
result = f(3);

% Built-in functions
sin(pi/2)
cos(0)
exp(1)
log(10)
sqrt(16)

Control Flow

Control
% if-elseif-else
x = 10;
if x > 0
    disp('Positive');
elseif x < 0
    disp('Negative');
else
    disp('Zero');
end

% switch-case
day = 'Monday';
switch day
    case 'Monday'
        disp('Start of week');
    case 'Friday'
        disp('End of week');
    otherwise
        disp('Mid week');
end

% try-catch
try
    result = 10 / 0;
catch ME
    disp(['Error: ' ME.message]);
end

Loops

Loops
% for loop
for i = 1:10
    disp(i);
end

% for loop with array
arr = [1, 2, 3, 4, 5];
for element = arr
    disp(element);
end

% while loop
count = 0;
while count < 5
    count = count + 1;
    disp(count);
end

% break and continue
for i = 1:10
    if i == 5
        break;      % Exit loop
    end
    if i == 3
        continue;   % Skip iteration
    end
    disp(i);
end

Plotting

Plotting
% Basic 2D plot
x = 0:0.1:2*pi;
y = sin(x);
plot(x, y);
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');
grid on;

% Multiple plots
plot(x, sin(x), 'r-', x, cos(x), 'b--');
legend('sin(x)', 'cos(x)');

% Subplots
subplot(2, 1, 1);
plot(x, sin(x));
title('Sine');

subplot(2, 1, 2);
plot(x, cos(x));
title('Cosine');

% 3D plot
[X, Y] = meshgrid(-2:0.2:2);
Z = X.^2 + Y.^2;
surf(X, Y, Z);

File I/O

File I/O
% Save and load MATLAB files
data = rand(5, 5);
save('data.mat', 'data');
load('data.mat');

% Read/write CSV files
csvwrite('data.csv', data);
loaded_data = csvread('data.csv');

% Read/write text files
fid = fopen('data.txt', 'w');
fprintf(fid, '%f %f %f\n', data);
fclose(fid);

% Read text file
fid = fopen('data.txt', 'r');
text_data = fscanf(fid, '%f');
fclose(fid);

% Import data from Excel
[num, txt, raw] = xlsread('data.xlsx');

Strings

Strings
% Basic strings
str1 = 'Hello World';
str2 = "Hello World";  % Double quotes also work

% String arrays
names = ["Alice", "Bob", "Charlie"];
ages = [25, 30, 35];

% String concatenation
result = strcat('Hello', ' ', 'World');
result2 = ['Hello' ' ' 'World'];

% String functions
length(str1)           % Length of string
strcmp(str1, str2)     % String comparison
strfind(str1, 'o')     % Find substring
strrep(str1, 'o', '0') % Replace substring

% String formatting
fprintf('Name: %s, Age: %d\n', names(1), ages(1));

Cell Arrays

Cell Arrays
% Create cell array
cell_array = {1, 'hello', [1 2 3], {4 5}};

% Access elements
element1 = cell_array{1};    % Get value
element2 = cell_array(1);    % Get cell

% Cell array of strings
names = {'Alice', 'Bob', 'Charlie'};

% Cell array with different types
mixed_data = {42, 'text', rand(3,3), true};

% Convert to/from cell arrays
num2cell([1 2 3 4])          % Convert array to cell
cell2mat({1 2 3 4})          % Convert cell to array

% Cell array functions
iscell(mixed_data)           % Check if cell array
cellfun(@length, names)      % Apply function to each cell

Structures

Structures
% Create structure
person.name = 'John';
person.age = 30;
person.city = 'New York';

% Access fields
name = person.name;
age = person.age;

% Structure array
people(1).name = 'Alice';
people(1).age = 25;
people(2).name = 'Bob';
people(2).age = 30;

% Access structure array
first_person = people(1);
all_names = {people.name};

% Structure functions
fieldnames(person)           % Get field names
isfield(person, 'name')      % Check if field exists
rmfield(person, 'age')       % Remove field

% Convert to/from structure
struct('name', 'John', 'age', 30)

Mathematical Functions

Math
% Trigonometric functions
sin(pi/2)       % Sine
cos(0)          % Cosine
tan(pi/4)       % Tangent
asin(0.5)       % Arcsine
acos(0.5)       % Arccosine
atan(1)         % Arctangent

% Exponential and logarithmic
exp(1)          % e^x
log(10)         % Natural logarithm
log10(100)      % Base-10 logarithm
sqrt(16)        % Square root

% Rounding functions
round(3.7)      % Round to nearest integer
floor(3.7)      % Round down
ceil(3.2)       % Round up
fix(-3.7)       % Round toward zero

% Complex numbers
z = 3 + 4i;     % Complex number
abs(z)          % Magnitude
angle(z)        % Phase angle
real(z)         % Real part
imag(z)         % Imaginary part

Linear Algebra

Linear Algebra
% Matrix operations
A = [1 2; 3 4];
det(A)          % Determinant
inv(A)          % Inverse
rank(A)         % Rank
trace(A)        % Trace

% Eigenvalues and eigenvectors
[V, D] = eig(A);    % Eigenvalue decomposition
eigenvalues = diag(D);

% Matrix decompositions
[L, U] = lu(A);     % LU decomposition
[Q, R] = qr(A);     % QR decomposition
[U, S, V] = svd(A); % SVD decomposition

% Solving linear systems
b = [5; 6];
x = A \ b;          % Solve Ax = b
x2 = linsolve(A, b);

% Matrix functions
expm(A)         % Matrix exponential
logm(A)         % Matrix logarithm
sqrtm(A)        % Matrix square root

Statistics

Statistics
% Generate random data
data = randn(100, 1);  % Normal distribution

% Descriptive statistics
mean_val = mean(data);
median_val = median(data);
std_val = std(data);
var_val = var(data);
min_val = min(data);
max_val = max(data);

% Correlation
x = randn(100, 1);
y = 2*x + randn(100, 1);
correlation = corr(x, y);
corr_matrix = corrcoef(x, y);

% Random number generation
normal_data = normrnd(0, 1, 100, 1);    % Normal
exponential_data = exprnd(2, 100, 1);   % Exponential
uniform_data = unifrnd(0, 1, 100, 1);   % Uniform

% Hypothesis testing
[h, p] = ttest(data, 0);    % One-sample t-test
[h2, p2] = ttest2(x, y);    % Two-sample t-test

% Histogram and probability plots
histogram(data);
normplot(data);

Signal Processing

Signal
% Generate signal
t = 0:0.001:1;
signal = sin(2*pi*10*t) + 0.5*sin(2*pi*50*t) + 0.1*randn(size(t));

% FFT analysis
Y = fft(signal);
P2 = abs(Y/length(signal));
P1 = P2(1:length(signal)/2+1);
f = (0:(length(signal)/2))/length(signal);

% Filtering
[b, a] = butter(4, 0.1, 'low');  % Low-pass filter
filtered_signal = filtfilt(b, a, signal);

% Convolution
kernel = ones(1, 10)/10;
smoothed = conv(signal, kernel, 'same');

% Cross-correlation
correlation = xcorr(signal, filtered_signal);

% Window functions
window = hamming(64);
windowed_signal = signal(1:64) .* window';

Optimization

Optimization
% Define objective function
fun = @(x) x(1)^2 + x(2)^2;  % f(x,y) = x^2 + y^2

% Unconstrained optimization
x0 = [1, 1];  % Initial guess
[x_opt, fval] = fminunc(fun, x0);

% Constrained optimization
A = [1, 1];  % x + y <= 1
b = 1;
Aeq = [];    % No equality constraints
beq = [];
lb = [0, 0]; % x >= 0, y >= 0
ub = [];
[x_opt, fval] = fmincon(fun, x0, A, b, Aeq, beq, lb, ub);

% Nonlinear least squares
fun_lsq = @(x) [x(1) - 1; x(2) - 2; x(1)^2 + x(2)^2 - 5];
x0 = [0, 0];
[x_opt, resnorm] = lsqnonlin(fun_lsq, x0);

% Global optimization
options = optimoptions('fmincon', 'Algorithm', 'sqp');
[x_opt, fval] = fmincon(fun, x0, [], [], [], [], lb, ub, [], options);

Symbolic Math

Symbolic
% Define symbolic variables
syms x y z
f = x^2 + y^2 + z^2;

% Differentiation
df_dx = diff(f, x);
df_dy = diff(f, y);
df_dx2 = diff(f, x, 2);  % Second derivative

% Integration
int_f = int(f, x);       % Indefinite integral
int_f_def = int(f, x, 0, 1);  % Definite integral

% Solving equations
eq1 = x + y == 5;
eq2 = 2*x - y == 1;
solution = solve([eq1, eq2], [x, y]);

% Symbolic substitution
f_sub = subs(f, [x, y, z], [1, 2, 3]);

% Taylor series
taylor_series = taylor(sin(x), x, 0, 'Order', 5);

% Laplace transform
syms s t
F = laplace(exp(-t), t, s);
f_inv = ilaplace(F, s, t);

GUI Development

GUI
% Create figure and UI elements
fig = figure('Name', 'Simple GUI', 'Position', [100 100 400 300]);

% Create buttons
btn1 = uicontrol('Style', 'pushbutton', 'String', 'Plot', ...
    'Position', [20 20 80 30], 'Callback', @plot_callback);

btn2 = uicontrol('Style', 'pushbutton', 'String', 'Clear', ...
    'Position', [120 20 80 30], 'Callback', @clear_callback);

% Create text input
edit1 = uicontrol('Style', 'edit', 'String', '10', ...
    'Position', [220 20 60 30]);

% Callback functions
function plot_callback(~, ~)
    x = 0:0.1:2*pi;
    y = sin(x);
    plot(x, y);
    title('Sine Wave');
end

function clear_callback(~, ~)
    clf;
end

% App Designer (R2016a+)
% Use appdesigner command to open App Designer

Toolboxes

Toolboxes
% Check available toolboxes
ver

% Signal Processing Toolbox
if license('test', 'Signal_Toolbox')
    % Signal processing functions available
    [b, a] = butter(4, 0.1);
end

% Image Processing Toolbox
if license('test', 'Image_Toolbox')
    % Image processing functions available
    img = imread('image.jpg');
    img_gray = rgb2gray(img);
    img_filtered = medfilt2(img_gray);
end

% Control System Toolbox
if license('test', 'Control_Toolbox')
    % Control system functions available
    sys = tf([1], [1 2 1]);
    step(sys);
end

% Neural Network Toolbox
if license('test', 'Neural_Network_Toolbox')
    % Neural network functions available
    net = feedforwardnet(10);
    net = train(net, inputs, targets);
end

Debugging

Debugging
% Set breakpoints
dbstop in myfunction at 10
dbstop if error
dbstop if warning

% Debug commands
dbcont        % Continue execution
dbstep        % Step into
dbstep in     % Step into function
dbstep out    % Step out of function
dbquit        % Quit debugging

% Show debugging info
dbstack       % Show call stack
dbstatus      % Show breakpoints
dbclear all   % Clear all breakpoints

% Error handling
try
    result = risky_function();
catch ME
    disp(['Error: ' ME.message]);
    disp(['Line: ' num2str(ME.line)]);
    disp(['File: ' ME.file]);
end

% Profiling
profile on
% ... your code ...
profile off
profile viewer

Performance

Performance
% Vectorization (fast)
x = 1:1000;
y = sin(x);  % Vectorized operation

% vs Loop (slow)
y = zeros(size(x));
for i = 1:length(x)
    y(i) = sin(x(i));
end

% Preallocation
n = 1000;
result = zeros(n, 1);  % Preallocate
for i = 1:n
    result(i) = some_calculation(i);
end

% Memory management
clear unused_variable
pack  % Defragment memory

% Performance timing
tic;
% ... your code ...
elapsed_time = toc;

% Profiling
profile on
% ... code to profile ...
profile off
profile viewer

Best Practices

Best Practices
% Good function structure
function [output1, output2] = my_function(input1, input2)
    % MY_FUNCTION Brief description of what the function does
    %
    % Syntax:
    %   [output1, output2] = my_function(input1, input2)
    %
    % Inputs:
    %   input1 - Description of input1
    %   input2 - Description of input2
    %
    % Outputs:
    %   output1 - Description of output1
    %   output2 - Description of output2
    %
    % Example:
    %   [result1, result2] = my_function(5, 10);
    
    % Input validation
    validateattributes(input1, {'numeric'}, {'scalar', 'positive'});
    validateattributes(input2, {'numeric'}, {'scalar'});
    
    % Main computation
    try
        output1 = input1 + input2;
        output2 = input1 * input2;
    catch ME
        error('Computation failed: %s', ME.message);
    end
end

% Good variable naming
data_points = 1000;
time_vector = 0:0.01:10;
frequency_response = fft(signal);