MATLAB
Updated: September 10, 2025Categories: 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.
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 + 3j; % Complex number % Logical Type is_true = true; is_false = false; % Character and String char_val = 'A'; % Single character string_val = "Hello World"; % String (newer MATLAB versions)
Collection Types
matlab
1234567891011121314% 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');
Variables and Constants
matlab
12345678910111213141516% Variable naming (case-sensitive) user_name = 'JohnDoe'; totalCount = 100; % Constants (using uppercase convention) PI = 3.14159; 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
123456789101112% 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 % Logical indexing numbers = [1, 2, 3, 4, 5]; even_numbers = numbers(mod(numbers, 2) == 0);
Control Structures
Conditional Statements
matlab
12345678910111213141516% If-ElseIf-Else score = 85; if score >= 90 grade = 'A'; elseif score >= 80 grade = 'B'; elseif score >= 70 grade = 'C'; else grade = 'F'; end % Ternary-like operator result = (score >= 60) ? 'Pass' : 'Fail';
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
123456789101112131415161718% 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);
Matrix Operations
matlab
12345678910111213141516% 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'; % Transpose inverse_A = inv(A); % Matrix inverse determinant = det(A); % Determinant
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
12345678910111213141516% Try-Catch Block try result = 10 / 0; catch ME disp('Error occurred'); disp(ME.message); end % Custom Error function divide(a, b) if b == 0 error('Cannot divide by zero'); end result = a / b; end
File I/O
matlab
12345678910111213141516171819% 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 File data = csvread('data.csv'); csvwrite('output.csv', data);
Data Visualization
matlab
12345678910111213141516171819202122% 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 figure; subplot(2,1,1); plot(x, sin(x)); subplot(2,1,2); plot(x, cos(x)); % 3D Plotting [X, Y] = meshgrid(-5:0.5:5); Z = X.^2 + Y.^2; surf(X, Y, Z);
Simulink and System Modeling
matlab
12345678910% Simulink basics typically involve graphical modeling % Requires Simulink toolbox % Script to create and simulate a simple model open_system('new_system'); add_block('simulink/Sources/Sine Wave', 'new_system/Sine Wave'); add_block('simulink/Sinks/Scope', 'new_system/Scope'); add_line('new_system', 'Sine Wave/1', 'Scope/1'); sim('new_system');
Toolbox Integration
matlab
1234567891011121314% 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');
Parallel Computing
matlab
123456789101112% Parallel Computing Toolbox features % Create parallel pool pool = parpool; % Parallel for loop parfor i = 1:1000 results(i) = some_computation(i); end % Close pool when done delete(pool);
Best Practices
matlab
123456789101112131415% Vectorization over loops % Slow for i = 1:length(data) result(i) = complex_function(data(i)); end % Fast (Vectorized) result = arrayfun(@complex_function, data); % Preallocate arrays result = zeros(1, 1000); % Preallocate before loop % Meaningful variable and function names % Use descriptive, context-specific names
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
Practice Platforms
Community
Continue Learning
Discover more cheatsheets to boost your productivity