Admin 13 Jun 2026 03:54

 

MATLAB Fundamentals Cheat Sheet

Introduction to MATLAB

MATLAB (Matrix Laboratory) is a high-performance programming language and computing environment widely used for mathematical computation, data analysis, algorithm development, and visualization. Its strength lies in matrix operations, making it particularly powerful for engineering and scientific applications.

Quick Tip: Always use the help command followed by a function name to get detailed information about any MATLAB function.

Basic Syntax and Structure

MATLAB code is executed in the Command Window or saved as script files (.m files). Statements typically end with a semicolon (;) to suppress output. Without a semicolon, MATLAB displays the result of the operation.

Hello World Example

% This is a comment in MATLABdisp('Hello, World!');  % Displays the textvariable = 5 + 3        % Calculations without semicolon show outputresult = variable * 2;  % Semicolon suppresses output

MATLAB is case-sensitive, meaning 'variables' and 'Variables' would be treated as different identifiers. Comments start with the percent (%) symbol.

Variables and Operations

Variables in MATLAB don't require explicit declaration. They are created when assigned their first value. MATLAB supports various data types including numeric, character, logical, and cell arrays.

Numeric Operations

x = 10;          % Integery = 3.1415;      % Floating-pointz = 2 + 3i;      % Complex number (real + imaginary*i)s = 'text';      % String (character array)

Arithmetic Operators

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
.* Element-wise multiplication a .* b
./ Element-wise division a ./ b
^ Matrix power a ^ 2
.^ Element-wise power a .^ 2

Warning: Pay attention to the difference between the dot (.) operator and the regular operator. The dot operator performs element-wise operations on arrays, while the regular operator performs matrix operations.

Control Flow

MATLAB provides standard control flow statements like loops, conditional statements, and switch cases.

Conditional Statements

if condition    % code to execute if condition is trueelseif another_condition    % code to execute if another_condition is trueelse    % code if none of the above conditions are trueend

For Loops

for i = 1:n    % code to execute n times    disp(i);end

While Loops

while condition    % code to execute while condition is true    % be sure to include code that changes the condition!end

Switch Statement

switch expression    case value1        % code if expression == value1    case value2        % code if expression == value2    otherwise        % code if none of the cases matchend

Matrices and Arrays

Matrices are the core data structure in MATLAB. They can be created directly using square brackets.

% Creating a row vectorv = [1, 2, 3];% Creating a column vectorw = [1; 2; 3];% Creating a 2x3 matrixA = [1, 2, 3; 4, 5, 6];% Creating a matrix using a rangeB = 1:5;          % Creates [1 2 3 4 5]C = 0:2:10;       % Creates [0 2 4 6 8 10]% Special matricesI = eye(3);       % 3x3 identity matrixZ = zeros(3,4);   % 3x4 matrix of zerosO = ones(2,5);    % 2x5 matrix of onesR = rand(3);      % 3x3 matrix of random numbers

Matrix Indexing

% Using parentheses to access elementsA(2,3)    % Element in 2nd row, 3rd columnA(2,:)    % 2nd row, all columnsA(:,3)    % All rows, 3rd column% Using colon rangesA(1:2,2:3)  % Submatrix with rows 1-2 and columns 2-3

Matrix Operations

Operation Description Example
A' Transpose of A A_transpose = A'
inv(A) Inverse of A A_inv = inv(A)
det(A) Determinant of A det = det(A)
rank(A) Rank of A r = rank(A)
eig(A) Eigenvalues of A eigenvalues = eig(A)

Plotting and Visualization

MATLAB offers powerful tools for data visualization. Here are some essential plotting functions:

Basic Plotting

% Two-dimensional line plotx = linspace(0, 2*pi, 100);y = sin(x);plot(x, y, 'r-', 'LineWidth', 2);xlabel('x');ylabel('y');title('Sine Wave');grid on;legend('sin(x)');

Common Plotting Functions

Function Description Example
plot 2D line plot plot(x,y)
scatter Scatter plot scatter(x,y)
bar Bar graph bar(x,y)
histogram Histogram histogram(data)
pie Pie chart pie(data)
surf 3D surface plot surf(Z)
contour Contour plot contour(Z)

Quick Tip: Use hold on to add multiple plots to the same figure and hold off to return to the default behavior.

Functions and File Organization

Functions are reusable blocks of code that accept inputs and return outputs. In MATLAB, functions are saved in .m files with the same name as the function.

Function Definition Example

function [output1, output2] = myFunction(input1, input2)    % Comments describing the function        % Function body    output1 = input1 + input2;    output2 = input1 * input2;end

Anonymous Functions

% Defining an anonymous functionsquare = @(x) x.^2;result = square(5);  % Returns 25

Useful Built-in Functions

Function Description Example
max/min Maximum/minimum value m = max(A)
mean Average value avg = mean(A)
std Standard deviation s = std(A)
sum Sum of elements s = sum(A)
sort Sort in ascending order sorted = sort(A)
find Find indices of specific elements indices = find(A > 5)
size Dimensions of array s = size(A)
length Length of longest dimension l = length(A)

Input/Output Operations

MATLAB provides various functions for handling input and output operations.

User Input and Output

% Display outputdisp('This is a message');fprintf('The value is %d\n', variable);  % Formatted output% Get user inputname = input('What is your name? ', 's');number = input('Enter a number: ');

File Input/Output

% Working with filessave('myData.mat');           % Save workspace to a fileload('myData.mat');           % Load from a file% Reading/writing text filesfileID = fopen('data.txt', 'w');fprintf(fileID, '%d %d\n', 10, 20);fclose(fileID);data = load('data.txt');

Warning: Always close files with fclose after opening them with fopen to prevent memory leaks and file access issues.

Debugging and Error Handling

Effective debugging is essential for developing reliable code. Here are some key MATLAB debugging tools:

Debugging Commands

Command Description
keyboard Pause execution and give control to keyboard
dbstop Set breakpoints
dbcont Continue execution
dbstep Step to next line
dbquit Exit debug mode

Error Handling

% Try-catch block for error handlingtry    % Code that might generate an error    result = compute_something();catch ME    % Error handling code    disp(['Error occurred: ', ME.message]);end

Common Error Messages

  • Undefined function or variable: Typically a spelling or capitalization error.
  • Index exceeds matrix dimensions: Trying to access an element outside the matrix bounds.
  • Inner matrix dimensions must agree: Incompatible matrices for multiplication.
  • Subscript indices must be real positive integers: Using invalid indices (e.g., negative numbers or 0).

Best Practices

  1. Always use meaningful variable names to improve code readability
  2. Comment your code extensively to explain complex operations
  3. Vectorize your code when possible to improve performance
  4. Use the MATLAB Profiler to identify bottlenecks in your code
  5. Test your code incrementally during development
  6. Make use of local functions to organize your code better

Reference Files For MATLAB Fundamentals Cheat Sheet
Screenshoot
File Name
ml_cheatsheet.pdf

File Size
0.19 MB

File Type
PDF

File Site
Description
This file is just a reference file for MATLAB Fundamentals Cheat Sheet. Does not guarantee that the specific things you want are included in it.
Direct download (wait 10 seconds)

MATLAB Fundamentals Cheat Sheet and Reference File Download Link


admin
Admin
2026-06-13 03:54:12

MATLAB Cheat Sheet For Calculus and Reference File Download Link


admin
Admin
2026-06-09 05:32:15

- **Sheet 1**: "harga Satuan Upah Dan Bahan" - **Sheet 2**: "pagar Beton" - **Sheet 3**:...


admin
Admin
2026-05-30 02:15:06

Forex Cheat Sheet and Reference File Download Link


admin
Admin
2026-06-06 20:58:17

Therapy Interventions Cheat Sheet and Reference File Download Link


admin
Admin
2026-06-07 04:34:10