MATLAB
Updated: May 22, 2026Categories: Languages, Scientific
Printed from:
MATLAB Cheatsheet
Language Overview
MATLAB (Matrix Laboratory) is a high-level programming language and numerical computing environment developed by MathWorks. It specializes in scientific computing, signal and image processing, and algorithm development with strong capabilities in matrix operations, data visualization, and technical computing across various domains including engineering, physics, economics, and signal processing. Recent releases have added expanded support for string arrays, tall arrays, GPU/parallel computing, and integration with Python, C/C++, and modern AI/deep learning workflows.
Basic Syntax
matlab
12345678910111213% Single line comment %{ Multi-line comment using block comment syntax %} % Print statement disp('Hello, World!'); % Suppress output with semicolon x = 5 + 3; % Calculation without display disp(x); % Explicit display
Data Types
Primitive Types
matlab
12345678910111213% Numeric Types integer_val = int32(42); % 32-bit integer float_val = 3.14159; % Double-precision floating point complex_val = 2 + 3i; % Complex number (1i / 1j are also valid) % Logical Type is_true = true; is_false = false; % Character and String char_val = 'A'; % Single character (char array) string_val = "Hello World"; % String scalar (recommended for text data)
Collection Types
matlab
1234567891011121314151617181920% Arrays (Fundamental in MATLAB) % Numeric Arrays numbers = [1, 2, 3, 4, 5]; % Row vector column_vector = [1; 2; 3; 4; 5]; % Column vector % Matrix matrix = [1 2 3; 4 5 6; 7 8 9]; % 3x3 matrix % Cell Arrays (Mixed-type container) cell_array = {42, 'text', [1 2 3]}; % Struct Arrays person = struct('name', 'John', 'age', 30, 'city', 'New York'); % Tables (recommended for tabular/mixed-type data) T = table(["Alice"; "Bob"], [30; 25], 'VariableNames', {'Name','Age'}); % Dictionaries (introduced in R2022b) d = dictionary(["apple","banana"], [1, 2]);
Variables and Constants
matlab
12345678910111213141516% Variable naming (case-sensitive) user_name = 'JohnDoe'; totalCount = 100; % Constants (using uppercase convention; MATLAB has no true const keyword) PI = pi; % Built-in constant GRAVITY = 9.81; % Multiple assignment [a, b, c] = deal(1, 2, 3); % Workspace management who % List current variables whos % Detailed variable information clear x % Remove specific variable
Operators
Arithmetic Operators
matlab
123456789% Basic arithmetic a = 10; b = 3; add_result = a + b; % Addition sub_result = a - b; % Subtraction mult_result = a * b; % Multiplication div_result = a / b; % Division power_result = a ^ b; % Exponentiation mod_result = mod(a, b); % Modulus
Comparison Operators
matlab
123456789% Comparison returns logical array x = [1, 2, 3, 4, 5]; y = [5, 4, 3, 2, 1]; equal = x == y; % Element-wise equality not_equal = x ~= y; % Element-wise inequality greater = x > y; % Element-wise greater than less_equal = x <= y; % Element-wise less or equal
Logical Operators
matlab
1234567891011121314% Logical operations a = true; b = false; and_result = a & b; % Element-wise AND or_result = a | b; % Element-wise OR not_result = ~a; % Logical NOT short_and = a && b; % Short-circuit AND (scalars) short_or = a || b; % Short-circuit OR (scalars) % Logical indexing numbers = [1, 2, 3, 4, 5]; even_numbers = numbers(mod(numbers, 2) == 0);
Control Structures
Conditional Statements
matlab
123456789101112131415161718192021222324252627282930% If-ElseIf-Else score = 85; if score >= 90 grade = 'A'; elseif score >= 80 grade = 'B'; elseif score >= 70 grade = 'C'; else grade = 'F'; end % MATLAB has no ternary (?:) operator. Common replacements: result = "Fail"; if score >= 60, result = "Pass"; end % Or using a helper / element-wise selection: result_vec = ["Fail" "Pass"]( (score >= 60) + 1 ); % Switch switch grade case {'A','B'} disp('Great'); case 'C' disp('OK'); otherwise disp('Needs work'); end
Loops
matlab
1234567891011121314151617181920212223% For Loop for i = 1:5 disp(i); end % While Loop count = 0; while count < 5 count = count + 1; disp(count); end % Break and Continue for j = 1:10 if j == 3 continue; % Skip iteration end if j == 7 break; % Exit loop end disp(j); end
Functions
Function Definition
matlab
12345678910111213141516171819202122232425262728293031323334353637% Basic function function result = add(x, y) result = x + y; end % Anonymous Functions square = @(x) x.^2; % Multiple Return Values function [sum_val, avg_val] = compute_stats(numbers) sum_val = sum(numbers); avg_val = mean(numbers); end % Function Handles func_handle = @sin; result = func_handle(pi/2); % Argument Validation (R2019b+) function y = scale(x, factor) arguments x (1,:) double factor (1,1) double = 1.0 end y = x * factor; end % Name-Value arguments (R2021a+) function plotIt(x, y, opts) arguments x, y opts.Color string = "blue" opts.Width double = 1.5 end plot(x, y, 'Color', opts.Color, 'LineWidth', opts.Width); end
Matrix Operations
matlab
123456789101112131415161718192021% Matrix Creation A = [1 2 3; 4 5 6; 7 8 9]; B = zeros(3, 3); % Zero matrix C = ones(2, 4); % Matrix of ones D = rand(3, 3); % Random matrix % Matrix Arithmetic matrix_sum = A + B; matrix_product = A * B; element_wise_mult = A .* B; % Dot operator for element-wise operations % Matrix Transformations transpose_A = A'; % Complex-conjugate transpose plain_T = A.'; % Plain (non-conjugate) transpose inverse_A = inv(A); % Matrix inverse (prefer A\b for solving Ax=b) determinant = det(A); % Solving linear systems (preferred over inv) b = [1; 2; 3]; x = A \ b; % Backslash operator
Object-Oriented Programming
matlab
1234567891011121314151617181920212223% Class Definition classdef Rectangle properties Length Width end methods function obj = Rectangle(l, w) obj.Length = l; obj.Width = w; end function area = getArea(obj) area = obj.Length * obj.Width; end end end % Usage rect = Rectangle(5, 3); area = rect.getArea();
Error Handling
matlab
1234567891011121314151617% Try-Catch Block try result = 10 / 0; % Note: returns Inf, not an error in MATLAB catch ME disp('Error occurred'); disp(ME.identifier); disp(ME.message); end % Custom Error with identifier function r = safeDivide(a, b) if b == 0 error('safeDivide:divideByZero', 'Cannot divide by zero'); end r = a / b; end
File I/O
matlab
12345678910111213141516171819202122232425% Text File I/O % Write fileID = fopen('output.txt', 'w'); fprintf(fileID, 'Hello, MATLAB\n'); fclose(fileID); % Read fileID = fopen('input.txt', 'r'); data = textscan(fileID, '%s'); fclose(fileID); % MAT File (MATLAB's native format) save('data.mat', 'variable1', 'variable2'); load('data.mat'); % CSV / spreadsheet (modern functions; csvread/csvwrite/xlsread are not recommended) M = readmatrix('data.csv'); % Numeric matrix writematrix(M, 'output.csv'); T = readtable('data.csv'); % Table with mixed types and headers writetable(T, 'output.csv'); % Timetables for time-stamped data TT = readtimetable('data.csv');
Data Visualization
matlab
123456789101112131415161718192021222324% Basic Plotting x = linspace(0, 2*pi, 100); y = sin(x); % Line Plot plot(x, y, 'r-', 'LineWidth', 2); title('Sine Wave'); xlabel('x'); ylabel('sin(x)'); % Multiple Plots with tiledlayout (preferred over subplot since R2019b) figure; tiledlayout(2,1); nexttile; plot(x, sin(x)); title('sin'); nexttile; plot(x, cos(x)); title('cos'); % 3D Plotting [X, Y] = meshgrid(-5:0.5:5); Z = X.^2 + Y.^2; surf(X, Y, Z); % Export graphics (preferred over print/saveas for figures) exportgraphics(gcf, 'figure.png', 'Resolution', 300);
Simulink and System Modeling
matlab
1234567891011% Simulink basics typically involve graphical modeling % Requires Simulink toolbox % Script to create and simulate a simple model new_system('mymodel'); open_system('mymodel'); add_block('simulink/Sources/Sine Wave', 'mymodel/Sine Wave'); add_block('simulink/Sinks/Scope', 'mymodel/Scope'); add_line('mymodel', 'Sine Wave/1', 'Scope/1'); sim('mymodel');
Toolbox Integration
matlab
12345678910111213141516171819% Check installed toolboxes ver % List installed toolboxes % Example: Signal Processing Toolbox Fs = 1000; % Sampling frequency t = 0:1/Fs:1; % Time vector x = sin(2*pi*50*t) + 0.5*randn(size(t)); filtered_x = lowpass(x, 100, Fs); % Image Processing img = imread('image.jpg'); gray_img = rgb2gray(img); edge_img = edge(gray_img, 'Sobel'); % Deep Learning Toolbox (modern API) net = imagePretrainedNetwork("resnet50"); % R2024a+ unified loader % (older "resnet50" / "alexnet" standalone functions are deprecated in favor of % imagePretrainedNetwork)
Parallel and GPU Computing
matlab
12345678910111213141516171819% Parallel Computing Toolbox features % Create parallel pool (auto-starts on first parfor in most setups) pool = parpool; % Default process-based pool % pool = parpool("Threads"); % Thread-based pool (lower overhead, since R2020a) % Parallel for loop results = zeros(1, 1000); parfor i = 1:1000 results(i) = some_computation(i); end % GPU arrays (requires Parallel Computing Toolbox + supported GPU) A = gpuArray(rand(1000)); B = A * A'; % Runs on GPU C = gather(B); % Bring back to CPU memory % Close pool when done delete(pool);
Interoperability
matlab
123456789101112% Call Python from MATLAB py.list({1, 2, 3}); np = py.importlib.import_module('numpy'); arr = np.array([1, 2, 3]); % Call MATLAB from Python (via the matlabengine package) % pip install matlabengine % Call C/C++ via MEX or the C++ Interface % Call REST APIs data = webread("https://api.example.com/data.json");
Best Practices
matlab
1234567891011121314151617181920212223242526% Vectorization over loops % Slow for i = 1:length(data) result(i) = sin(data(i)) + 1; end % Fast (true vectorization — built-ins are already element-wise) result = sin(data) + 1; % Preallocate arrays result = zeros(1, 1000); % Preallocate before loop % Prefer string arrays over char arrays for text data names = ["Alice", "Bob", "Carol"]; % Prefer tables/timetables over parallel arrays for mixed data % Use the arguments block for input validation in functions % Use local functions and packages (+folders) to organize code % Profile before optimizing profile on % ... code ... profile viewer
Resources for Further Learning
Official Documentation
Books
- "MATLAB for Engineers" by Holly Moore
- "Mastering MATLAB" by Duane Hanselman
- "MATLAB: A Practical Introduction to Programming and Problem Solving" by Stormy Attaway
Online Learning
- MathWorks MATLAB Onramp (free)
- MathWorks Self-Paced Courses
- Coursera MATLAB Courses
- edX MATLAB Courses
Practice Platforms
Community
Continue Learning
Discover more cheatsheets to boost your productivity