Lecture 1 / 12
Lecture 01 Β· Fundamentals

Introduction to MATLAB & Setup

Beginner ~50 min

What is MATLAB?

MATLAB (MATrix LABoratory) is a high-level programming language and interactive environment developed by MathWorks for numerical computing, data analysis, algorithm development, and visualization. It is widely used in engineering, science, and academia.

Unlike traditional programming languages that focus heavily on low-level implementation details, MATLAB is designed to help users solve mathematical and technical problems quickly using simple, readable syntax. It allows engineers, students, and researchers to work efficiently with numbers, matrices, graphs, simulations, and large datasets.

MATLAB combines programming, mathematics, and visualization into a single environment. This means you can write code, perform calculations, visualize results, and analyze data all in one place.

Why MATLAB?

  • Built-in matrix and array operations
  • Outstanding visualization tools
  • Rich ecosystem of toolboxes
  • Industry standard in engineering and research
  • Easy-to-read syntax for beginners
  • Powerful numerical computation capabilities
  • Excellent support for simulations and modeling

Where is MATLAB Used?

  • Signal processing and communications
  • Machine learning and artificial intelligence
  • Control systems engineering
  • Robotics and automation
  • Image and video processing
  • Financial analysis and modeling
  • Scientific research and data visualization

Understanding the MATLAB Environment

When you open MATLAB for the first time, you will see several important sections of the interface. Understanding these sections will help you work more efficiently.

  • Command Window: Used to execute MATLAB commands directly.
  • Editor: Used for writing and saving MATLAB scripts and programs.
  • Workspace: Displays variables currently stored in memory.
  • Current Folder: Shows files and scripts in the active directory.
  • Command History: Stores previously executed commands.

The Command Window is ideal for quick calculations and testing commands, while the Editor is used for writing reusable scripts and larger programs.

Installation & Setup

Download MATLAB from mathworks.com. Use the online version (MATLAB Online) if you prefer no installation.

During installation, you may be asked to sign in with a MathWorks account and select the products you want to install. Beginners can start with the default installation settings.

Minimum Steps to Install MATLAB

  • Create or sign in to your MathWorks account
  • Download the MATLAB installer
  • Select your license or trial version
  • Choose the installation location
  • Install recommended toolboxes
  • Launch MATLAB after installation completes

MATLAB Online vs Desktop Version

  • MATLAB Online: Runs in your browser without installation.
  • Desktop MATLAB: Provides better performance and offline access.
MATLAB Command Window
>> disp('Hello, MATLAB Mastery!')
Hello, MATLAB Mastery!

>> version
ans = 
    '9.14.0.XXXXXX (R2023a)'

The disp() function is used to display text or values in the Command Window. The version command shows the currently installed MATLAB version.

Basic MATLAB Commands

Basic Commands
>> clc
>> clear
>> who
>> pwd
  • clc clears the Command Window.
  • clear removes variables from memory.
  • who displays active variables.
  • pwd shows the current working directory.

Creating Your First MATLAB Script

A MATLAB script is a file containing multiple MATLAB commands saved with the .m extension.

  1. Open the MATLAB Editor
  2. Create a new script
  3. Write MATLAB commands
  4. Save the file with a .m extension
  5. Run the script using the Run button
first_script.m
clc
clear

name = 'John';
todayDate = datestr(now);

disp(['Hello, ' name])
disp(['Today is: ' todayDate])

This script demonstrates how to create variables, combine strings, and display output using MATLAB commands.

πŸ’» Try It Yourself - Multi-Language Compiler

Practice MATLAB and many other programming languages right here in your browser! Switch between languages, modify the code, and click "Run" to see results instantly.

πŸ’‘ Practice Tips:

  • Switch to MATLAB in the language selector and try the numerical computing examples
  • Experiment with MATLAB's matrix operations and plotting capabilities
  • Try other numerical languages like Python, R, or compare with scientific computing concepts
  • Use the "Load Example" button to see MATLAB-specific code samples
  • Use Ctrl+Enter to quickly run your code

Important Notes for Beginners

  • MATLAB is case-sensitive. Variables like Age and age are different.
  • Every command entered in the Command Window executes immediately.
  • Use semicolons ; to suppress output in MATLAB.
  • Save your scripts frequently while coding.
  • Practice commands in the Command Window before writing larger scripts.
🎯 Exercise 1.1

Open MATLAB, run the command ver to see your version, and create a simple script that prints your name and today's date using datestr(now).

🎯 Exercise 1.2

Create a script that stores your age in a variable and displays a welcome message using disp().

🎯 Exercise 1.3

Practice the commands clc, clear, who, and pwd in the Command Window and observe their outputs.

Lecture 02 Β· Fundamentals

Variables & Matrices

Beginner ~45 min

Matrices: The Core of MATLAB

In MATLAB, everything is a matrix. A single number is a 1x1 matrix.

MATLAB was originally designed for matrix computations, which is why matrices are the foundation of the language. Whether you work with numbers, images, datasets, or signals, MATLAB internally handles them as matrices or arrays.

Understanding matrices is one of the most important skills in MATLAB because nearly every operation involves matrix manipulation.

% Row vector
r = [1 2 3];

% Column vector
c = [1; 2; 3];

% 2x2 Matrix
M = [1 2; 3 4];

Square brackets [] are used to create matrices in MATLAB.

  • Spaces or commas separate columns.
  • Semicolons ; separate rows.
  • All rows in a matrix must contain the same number of elements.

Understanding Variables

Variables are used to store data in MATLAB. A variable can store numbers, matrices, text, or other types of information.

age = 21;
name = 'Alex';
piValue = 3.1416;

In MATLAB, variables are created automatically when you assign values to them.

Rules for Variable Names

  • Variable names must start with a letter.
  • They can contain letters, numbers, and underscores.
  • Spaces are not allowed.
  • MATLAB is case-sensitive.
% Valid variable names
score = 90;
student_name = 'John';

% Invalid variable names
% 2score = 50
% student name = 'Alex'

Creating Different Types of Matrices

Row Vectors

A row vector contains elements arranged horizontally.

rowVector = [10 20 30 40];

Column Vectors

A column vector contains elements arranged vertically.

columnVector = [10; 20; 30; 40];

Multi-Dimensional Matrices

Matrices can contain multiple rows and columns.

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

Accessing Matrix Elements

You can access individual elements of a matrix using row and column indices.

M = [1 2; 3 4];

M(1,1)
M(2,2)

MATLAB indexing starts from 1, not 0 like many programming languages.

  • M(1,1) accesses the first row and first column.
  • M(2,2) accesses the second row and second column.

Basic Matrix Operations

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

% Addition
A + B

% Subtraction
A - B

% Matrix multiplication
A * B

MATLAB allows you to perform matrix calculations easily using simple operators.

  • + performs matrix addition
  • - performs matrix subtraction
  • * performs matrix multiplication

Creating Special Matrices

MATLAB provides built-in functions for creating commonly used matrices.

  • zeros(3,3): 3x3 matrix of zeros
  • ones(2,4): 2x4 matrix of ones
  • eye(3): 3x3 Identity matrix
% Matrix of zeros
Z = zeros(3,3)

% Matrix of ones
O = ones(2,4)

% Identity matrix
I = eye(3)

Useful Matrix Functions

A = [1 2 3; 4 5 6];

size(A)
length(A)
numel(A)
  • size(A) returns the dimensions of the matrix.
  • length(A) returns the largest dimension.
  • numel(A) returns the total number of elements.

Displaying Variables

MATLAB automatically displays results if a semicolon is not used.

x = 10
y = 20;

disp(x)
disp(y)

Adding a semicolon ; suppresses the output in the Command Window.

Important Notes for Beginners

  • MATLAB stores data in matrix form by default.
  • Always ensure matrix dimensions are compatible for operations.
  • Use meaningful variable names for better code readability.
  • Practice matrix creation regularly to build confidence.
  • Remember that MATLAB indexing starts at 1.
🎯 Exercise 2.1

Create a row vector containing five numbers and a column vector containing the same numbers.

🎯 Exercise 2.2

Create a 3x3 matrix and display its second row and third column element.

🎯 Exercise 2.3

Create matrices using zeros(), ones(), and eye() functions.

🎯 Exercise 2.4

Create two matrices and perform addition, subtraction, and multiplication operations.

Lecture 03 Β· Fundamentals

Operators & Expressions

Beginner ~50 min

Understanding Operators in MATLAB

Operators are symbols used to perform mathematical, logical, and comparison operations on data. MATLAB provides a wide variety of operators that work with numbers, vectors, and matrices.

Expressions are combinations of variables, values, and operators that MATLAB evaluates to produce a result.

a = 10;
b = 5;

sumValue = a + b
difference = a - b
product = a * b
division = a / b

MATLAB evaluates expressions from left to right while following operator precedence rules.

Arithmetic Operators

Arithmetic operators are used for mathematical calculations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
^ Power a ^ 2
x = 4;
y = 2;

x + y
x - y
x * y
x / y
x ^ y

Element-wise vs Matrix Operations

This is a critical concept in MATLAB. Use a dot . for element-wise operations.

MATLAB supports two types of operations when working with matrices:

  • Matrix Operations: Follow mathematical matrix rules.
  • Element-wise Operations: Perform operations on corresponding elements individually.
A = [1 2; 3 4];
B = [2 2; 2 2];

C1 = A * B; % Matrix multiplication

C2 = A .* B; % Element-wise multiplication
% Result: [1*2 2*2; 3*2 4*2]

The dot operator . tells MATLAB to apply the operation to each element separately.

Element-wise Operators

Operator Description
.* Element-wise multiplication
./ Element-wise division
.^ Element-wise power
A = [1 2 3];
B = [4 5 6];

A .* B
A ./ B
A .^ 2

Comparison Operators

Comparison operators compare values and return logical results such as 1 (true) or 0 (false).

Operator Description
== Equal to
~= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
a = 10;
b = 20;

a == b
a ~= b
a > b
a < b

Logical Operators

Logical operators are used to combine multiple conditions.

Operator Description
&& Logical AND
|| Logical OR
~ Logical NOT
x = 5;

x > 0 && x < 10
x == 5 || x == 8
~(x == 5)

Order of Operations

MATLAB follows standard mathematical precedence rules while evaluating expressions.

  1. Parentheses ()
  2. Powers ^
  3. Multiplication and Division
  4. Addition and Subtraction
result1 = 2 + 3 * 4
result2 = (2 + 3) * 4

Using parentheses improves readability and avoids unexpected results.

Using Built-in Mathematical Functions

MATLAB includes many built-in mathematical functions for calculations.

sqrt(25)
abs(-10)
round(3.7)
max([1 5 2])
min([1 5 2])
  • sqrt() calculates square roots.
  • abs() returns absolute values.
  • round() rounds numbers.
  • max() finds the maximum value.
  • min() finds the minimum value.

Important Notes for Beginners

  • Use element-wise operators when working with individual matrix elements.
  • Matrix multiplication requires compatible matrix dimensions.
  • Always check whether you need matrix operations or element-wise operations.
  • Use parentheses to make expressions easier to understand.
  • Logical operators are commonly used in conditions and loops.
🎯 Exercise 3.1

Create two matrices and perform matrix multiplication and element-wise multiplication.

🎯 Exercise 3.2

Write expressions using arithmetic operators and observe the outputs.

🎯 Exercise 3.3

Practice comparison operators using different variable values.

🎯 Exercise 3.4

Use the functions sqrt(), abs(), and round() with different inputs.

Lecture 04 Β· Fundamentals

Control Flow

Beginner ~40 min

What is Control Flow?

Control flow determines how MATLAB executes different parts of a program based on conditions, decisions, and repetition. It allows programs to become dynamic and intelligent instead of executing every line sequentially.

Using control flow statements, you can:

  • Make decisions using conditions
  • Repeat tasks automatically using loops
  • Execute different blocks of code based on user input or data

Conditional Logic

Conditional statements allow MATLAB to execute specific code only when certain conditions are true.

if x > 0
    disp('Positive')
elseif x < 0
    disp('Negative')
else
    disp('Zero')
end

The program checks conditions from top to bottom.

  • if checks the first condition.
  • elseif checks additional conditions.
  • else runs if none of the conditions are true.
  • end marks the end of the conditional block.

Simple if Statement

Use a simple if statement when only one condition needs to be checked.

age = 20;

if age >= 18
    disp('You are eligible to vote.')
end

If the condition is true, MATLAB executes the code inside the block.

if-else Statement

The if-else structure provides an alternative action when a condition is false.

marks = 45;

if marks >= 50
    disp('Pass')
else
    disp('Fail')
end

Nested Conditions

You can place one conditional statement inside another conditional statement.

number = 15;

if number > 0
    if mod(number,2) == 0
        disp('Positive Even Number')
    else
        disp('Positive Odd Number')
    end
end

The mod() function returns the remainder after division.

Switch Statement

The switch statement is useful when comparing a variable against multiple fixed values.

day = 3;

switch day
    case 1
        disp('Monday')
    case 2
        disp('Tuesday')
    case 3
        disp('Wednesday')
    otherwise
        disp('Invalid Day')
end
  • case defines possible matching values.
  • otherwise executes if no cases match.

Introduction to Loops

Loops allow MATLAB to repeat a block of code multiple times automatically.

MATLAB mainly provides two types of loops:

  • for loop β€” repeats code a fixed number of times
  • while loop β€” repeats code while a condition remains true

for Loop

A for loop is used when the number of repetitions is known in advance.

for i = 1:5
    disp(i)
end

This loop displays numbers from 1 to 5.

Loop with Step Size

for i = 0:2:10
    disp(i)
end

The syntax start:step:end controls the increment value.

while Loop

A while loop runs repeatedly as long as the condition remains true.

x = 1;

while x <= 5
    disp(x)
    x = x + 1;
end

Be careful when using while loops because incorrect conditions may create infinite loops.

Loop Control Statements

MATLAB provides special statements to control loop execution.

break Statement

The break statement immediately exits a loop.

for i = 1:10
    if i == 5
        break
    end
    disp(i)
end

continue Statement

The continue statement skips the current iteration and moves to the next one.

for i = 1:5
    if i == 3
        continue
    end
    disp(i)
end

Important Notes for Beginners

  • Always close conditional and loop blocks using end.
  • Use proper indentation to improve readability.
  • for loops are best when the number of repetitions is known.
  • while loops are useful when repetition depends on conditions.
  • Test conditions carefully to avoid infinite loops.
🎯 Exercise 4.1

Write a program that checks whether a number is positive, negative, or zero.

🎯 Exercise 4.2

Create a for loop that displays numbers from 1 to 20.

🎯 Exercise 4.3

Create a while loop that prints even numbers from 2 to 10.

🎯 Exercise 4.4

Use a switch statement to display the name of a month based on a numeric value.

Lecture 05 Β· Fundamentals

Scripts & Functions

Beginner ~50 min

What are Scripts and Functions?

Scripts and functions are two important ways to organize MATLAB code.

  • Scripts are files that execute MATLAB commands sequentially.
  • Functions are reusable blocks of code that perform specific tasks.

Using scripts and functions helps make programs cleaner, easier to manage, and easier to reuse.

Understanding MATLAB Scripts

A MATLAB script is a file that contains a series of MATLAB commands saved with the .m extension.

Scripts are useful for:

  • Performing calculations
  • Automating repetitive tasks
  • Testing MATLAB commands
  • Writing simple programs
% firstScript.m

clc
clear

name = 'Alex';
age = 21;

disp(['Name: ' name])
disp(['Age: ' num2str(age)])

Save the file with a meaningful name such as firstScript.m and run it using the MATLAB Run button.

Advantages of Scripts

  • Easy to write and execute
  • Useful for beginners
  • Can execute multiple commands together
  • Good for quick calculations and experiments

What is a Function?

A function is a reusable block of code designed to perform a specific task.

Functions can:

  • Accept inputs
  • Process data
  • Return outputs

Functions improve code reusability and reduce duplication in programs.

Creating a Function

function area = calcCircleArea(r)
    area = pi * r^2;
end

This function calculates the area of a circle using the formula:

Area = Ο€rΒ²
  • function defines a MATLAB function.
  • area is the output variable.
  • calcCircleArea is the function name.
  • r is the input parameter.

The function file name must match the function name.

Calling a Function

After creating the function, you can call it from the Command Window or another script.

result = calcCircleArea(5)

disp(result)

MATLAB passes the value 5 into the function as the radius.

Functions with Multiple Inputs

Functions can accept more than one input argument.

function sumValue = addNumbers(a, b)
    sumValue = a + b;
end
result = addNumbers(10, 20)

Functions with Multiple Outputs

MATLAB functions can also return multiple output values.

function [sumValue, productValue] = calculate(a, b)
    sumValue = a + b;
    productValue = a * b;
end
[s, p] = calculate(4, 5)

Variable Scope

Variables inside functions are usually local variables.

This means:

  • Variables created inside a function are not accessible outside the function.
  • Functions help prevent variable conflicts.
  • Scripts share variables with the base workspace.

Using Comments in Scripts and Functions

Comments help explain code and improve readability.

% This script calculates area

radius = 10;
area = pi * radius^2;

disp(area)

Comments begin with the % symbol in MATLAB.

Built-in MATLAB Functions

MATLAB already provides many built-in functions for calculations and analysis.

sqrt(25)
length([1 2 3 4])
max([5 8 2])
min([5 8 2])
  • sqrt() calculates square roots.
  • length() returns vector length.
  • max() finds the maximum value.
  • min() finds the minimum value.

Best Practices for Scripts and Functions

  • Use meaningful file and function names.
  • Keep functions focused on one task.
  • Write comments for complex logic.
  • Test functions with different inputs.
  • Organize scripts into smaller reusable functions.

Important Notes for Beginners

  • Function names and file names should match.
  • Functions must usually be saved in separate .m files.
  • Scripts execute line by line in the workspace.
  • Functions help make code modular and reusable.
  • Always test functions after creating them.
🎯 Exercise 5.1

Create a script that displays your name, age, and city.

🎯 Exercise 5.2

Create a function that calculates the square of a number.

🎯 Exercise 5.3

Create a function that accepts two numbers and returns their sum and product.

🎯 Exercise 5.4

Write a script that calls a user-defined function multiple times using different inputs.

Lecture 06 Β· Core Concepts

Arrays & Matrix Operations

Intermediate ~55 min

Arrays and matrices are fundamental concepts in MATLAB and numerical computing. They are widely used in engineering, machine learning, physics, data science, graphics, and scientific simulations.

MATLAB is specially designed for matrix-based computations, which makes mathematical operations fast and efficient. Almost every value in MATLAB is stored internally as an array or matrix.

Understanding Arrays

An array is a collection of multiple values stored inside a single variable. Arrays allow developers and engineers to work with large datasets efficiently.

MATLAB supports:

  • 1D Arrays (Vectors)
  • 2D Arrays (Matrices)
  • Multi-dimensional Arrays

Creating Arrays

Arrays are created using square brackets []. Elements are separated using spaces or commas.

arr = [1 2 3 4 5]

rowVector = [10, 20, 30]

columnVector = [1; 2; 3; 4]

In this example:

  • arr creates a row array
  • rowVector uses commas for separation
  • columnVector uses semicolons to create a column vector

Accessing Array Elements

MATLAB uses indexing to access specific elements in arrays and matrices. Indexing starts from 1 instead of 0.

numbers = [5 10 15 20]

numbers(1)
numbers(3)

Output:

5
15

Here:

  • numbers(1) accesses the first element
  • numbers(3) accesses the third element

Matrix Basics

A matrix is a two-dimensional array containing rows and columns. Matrices are essential in linear algebra and scientific computing.

A = [1 2; 
     3 4]

This matrix contains:

  • 2 rows
  • 2 columns
  • 4 total elements

Matrix Addition & Subtraction

Matrices of the same dimensions can be added or subtracted.

A = [1 2; 3 4]

B = [5 6; 7 8]

A + B

A - B

MATLAB performs operations element by element.

Matrix Multiplication

Matrix multiplication follows mathematical linear algebra rules.

A = [1 2; 3 4]

B = [2 0; 1 2]

A * B

The * operator performs matrix multiplication.

Element-wise Operations

MATLAB also supports element-wise operations using the dot operator ..

A = [1 2; 3 4]

A .* A

A .^ 2

Here:

  • .* multiplies corresponding elements
  • .^ applies power to each element individually

Linear Algebra

MATLAB provides powerful built-in functions for solving linear algebra problems. These functions are heavily used in engineering, robotics, AI, and data science.

A = [1 2; 3 4];

inv(A) % Inverse

det(A) % Determinant

eig(A) % Eigenvalues

In this example:

  • inv(A) calculates the inverse of the matrix
  • det(A) calculates the determinant
  • eig(A) returns the eigenvalues

Understanding Matrix Inverse

The inverse of a matrix is useful for solving systems of equations. A matrix must be square and have a non-zero determinant to be invertible.

A = [2 1;
     5 3]

inv(A)

Determinants

The determinant is a special numeric value calculated from a square matrix. It helps determine whether a matrix is invertible.

A = [4 7;
     2 6]

det(A)

If the determinant equals zero, the matrix cannot be inverted.

Eigenvalues

Eigenvalues are important in machine learning, image processing, physics, and vibration analysis.

A = [3 1;
     0 2]

eig(A)

Eigenvalues describe important mathematical properties of matrices.

Special Matrix Functions

MATLAB provides several built-in functions for generating special matrices.

zeros(3,3)

ones(2,2)

eye(3)

These functions create:

  • zeros() β†’ Matrix filled with zeros
  • ones() β†’ Matrix filled with ones
  • eye() β†’ Identity matrix

Real-World Applications

  • Machine learning algorithms
  • Computer graphics
  • Engineering simulations
  • Signal processing
  • Image processing
  • Physics calculations

Best Practices

  • Use vectorized operations whenever possible
  • Avoid unnecessary loops for matrix calculations
  • Check matrix dimensions before operations
  • Use built-in MATLAB functions for efficiency
  • Write clean and readable matrix expressions

Summary

In this lecture, we learned about arrays and matrix operations in MATLAB. We explored how to create arrays, access elements, and perform matrix operations.

We also studied important linear algebra concepts such as matrix inverse, determinant, and eigenvalues using built-in MATLAB functions.

Arrays and matrices form the foundation of scientific computing and numerical programming in MATLAB.

Lecture 07 Β· Core Concepts

Plotting & Visualization

Intermediate ~60 min

Data visualization is one of the most important features of MATLAB. Instead of reading raw numbers from arrays or matrices, graphs help us understand patterns, trends, relationships, and behavior visually.

MATLAB provides powerful plotting functions for creating:

  • 2D graphs
  • 3D plots
  • Bar charts
  • Pie charts
  • Histograms
  • Scientific visualizations

Plotting is heavily used in:

  • Engineering
  • Machine Learning
  • Signal Processing
  • Statistics
  • Scientific Research

In this lecture, we will learn:

  • How to create 2D plots
  • How to customize graphs
  • How to add titles and labels
  • How to create multiple plots
  • How to create different chart types

2D Plotting

The plot() function is used to create 2D line graphs. It takes x-values and y-values as input and draws the graph.

x = 0:0.1:10;

y = sin(x);

plot(x, y, 'r--', 'LineWidth', 2);

title('Sine Wave');

xlabel('Time');

ylabel('Amplitude');

grid on;

Understanding the Example

  • 0:0.1:10 creates values from 0 to 10 with step 0.1
  • sin(x) calculates sine values
  • plot() draws the graph
  • 'r--' means red dashed line
  • LineWidth controls line thickness
  • title() adds graph title
  • xlabel() labels x-axis
  • ylabel() labels y-axis
  • grid on enables background grid

Plot Styles & Colors

MATLAB allows different colors, markers, and line styles to improve graph appearance.

x = 0:0.5:10;

y1 = x;

y2 = x.^2;

plot(x, y1, 'b-o');

hold on;

plot(x, y2, 'g:*');

legend('Linear', 'Quadratic');

grid on;

Common Plot Symbols

% Colors
'r'  % Red
'g'  % Green
'b'  % Blue
'k'  % Black

% Line styles
'-'   % Solid line
'--'  % Dashed line
':'   % Dotted line

% Markers
'o'   % Circle
'*'   % Star
'+'   % Plus

Multiple Plots

MATLAB can display multiple graphs in the same figure using subplot().

x = 0:0.1:10;

subplot(2,1,1);

plot(x, sin(x));

title('Sine Function');

subplot(2,1,2);

plot(x, cos(x));

title('Cosine Function');

Understanding subplot()

The syntax subplot(rows, columns, position) divides the figure window into sections.

  • 2 β†’ total rows
  • 1 β†’ total columns
  • 1 or 2 β†’ position number

Bar Charts

Bar charts are useful for comparing categories and discrete values.

students = [50 65 80 90];

bar(students);

title('Student Marks');

xlabel('Students');

ylabel('Marks');

Pie Charts

Pie charts show percentage distribution of data.

data = [30 25 20 25];

pie(data);

title('Market Share');

Histograms

Histograms display frequency distribution of data values.

values = randn(1,1000);

histogram(values);

title('Random Data Distribution');

3D Plotting

MATLAB also supports 3D visualizations for advanced mathematical and engineering analysis.

[X,Y] = meshgrid(-5:0.5:5);

Z = sin(sqrt(X.^2 + Y.^2));

surf(X, Y, Z);

title('3D Surface Plot');

Important 3D Functions

  • plot3() β†’ 3D line plot
  • surf() β†’ Surface plot
  • mesh() β†’ Wireframe mesh
  • contour() β†’ Contour map

Customizing Graphs

MATLAB provides many functions to improve graph readability and design.

x = 0:0.1:5;

y = exp(x);

plot(x, y, 'LineWidth', 3);

axis([0 5 0 150]);

grid on;

legend('e^x');

title('Exponential Function');

Best Practices

  • Always label graph axes clearly
  • Use titles for better understanding
  • Choose readable colors and styles
  • Use legends when plotting multiple graphs
  • Enable grids for scientific visualization
🎯 Exercise 7.1: Function Plotter

Create MATLAB programs that:

  • Plot sine, cosine, and tangent functions
  • Create multiple subplots in one figure
  • Customize line colors and markers
  • Add titles, labels, and legends
🎯 Exercise 7.2: Data Visualization

Create different chart types using sample datasets:

  • Create a bar chart of student marks
  • Create a pie chart for expenses
  • Create a histogram of random values
  • Create a 3D surface plot
Lecture 08 Β· Core Concepts

Data Import & Export

Intermediate ~45 min

Data Import and Export are essential skills in MATLAB for working with external datasets. Most real-world applications involve reading data from files, processing it, and exporting the results.

MATLAB supports multiple file formats such as CSV, Excel, text files, MAT files, and JSON files. These features make MATLAB highly useful for data analysis, machine learning, and scientific computing.

Introduction to Data Import

Importing data means loading external information into MATLAB for processing and analysis. Data may come from spreadsheets, databases, sensors, APIs, or other software systems.

MATLAB provides built-in functions that simplify reading and handling structured data.

Reading Data

One of the most common formats for storing tabular data is the CSV (Comma-Separated Values) file. MATLAB can easily read CSV files using the readtable() function.

T = readtable('data.csv');

data = T.Variables;

In this example:

  • readtable() imports the CSV file as a table
  • T stores the table data
  • T.Variables extracts the raw values from the table

Understanding Tables

Tables are one of the most useful data structures in MATLAB. They allow datasets to contain different types of data such as numbers, text, and dates.

T = table(
    ["Ali"; "Sara"; "John"],
    [20; 22; 21],
    [85; 90; 88]
)

Tables organize information into rows and columns similar to spreadsheets.

Previewing Imported Data

After importing data, it is important to inspect the dataset before performing analysis.

head(T)

summary(T)

size(T)

These functions help us understand the dataset:

  • head() displays the first rows
  • summary() provides information about columns
  • size() returns the dimensions of the table

Reading Excel Files

MATLAB can also import Excel spreadsheets using the readtable() function.

T = readtable('students.xlsx')

This automatically loads Excel sheet data into a MATLAB table.

Reading Text Files

Text files are commonly used for logs, configurations, and raw datasets.

data = readlines('notes.txt')

The readlines() function reads text files line by line.

Importing MAT Files

MAT files are MATLAB’s native file format used to store variables and workspace data.

load('dataset.mat')

The load() function imports variables directly into the current workspace.

Accessing Table Data

Individual rows and columns can be accessed using indexing or variable names.

T.Name

T(1,:)

T(:,2)

Here:

  • T.Name accesses the Name column
  • T(1,:) returns the first row
  • T(:,2) returns the second column

Data Cleaning Basics

Imported data may contain missing values, incorrect formatting, or duplicate entries. Cleaning data improves analysis accuracy.

rmmissing(T)

unique(T)

In this example:

  • rmmissing() removes missing data
  • unique() removes duplicate rows

Exporting Data

After processing data, results can be exported to external files for sharing or storage.

Writing CSV Files

writetable(T, 'output.csv')

The writetable() function exports table data to a CSV file.

Writing Excel Files

writetable(T, 'report.xlsx')

This saves the table data into an Excel spreadsheet.

Saving MATLAB Variables

MATLAB variables can also be saved directly into MAT files.

save('backup.mat')

This stores all workspace variables inside a MAT file.

Advantages of Data Import & Export

  • Enables integration with external software
  • Simplifies data analysis workflows
  • Supports multiple file formats
  • Improves data sharing and storage
  • Essential for scientific and business applications

Real-World Applications

  • Machine learning datasets
  • Business reporting systems
  • Scientific experiments
  • Financial analysis
  • Sensor and IoT systems
  • Data visualization projects

Best Practices

  • Always inspect imported data before analysis
  • Use tables for structured datasets
  • Clean missing and duplicate data
  • Use meaningful file names
  • Keep backup copies of important datasets

Summary

In this lecture, we learned how to import and export data in MATLAB. We explored reading CSV, Excel, text, and MAT files using built-in MATLAB functions.

We also learned how to access table data, clean datasets, and export processed information into external files.

Data Import and Export are critical skills for data analysis, machine learning, and scientific computing workflows.

Lecture 09 Β· Advanced

Symbolic Math

Advanced ~50 min

Symbolic Math in MATLAB allows mathematical expressions to be handled symbolically instead of numerically. This means MATLAB can work with variables, equations, derivatives, integrals, and algebraic expressions exactly as they appear in mathematics.

Symbolic computation is widely used in engineering, physics, machine learning, robotics, and scientific research. MATLAB provides powerful symbolic tools through the Symbolic Math Toolbox.

Introduction to Symbolic Variables

Before performing symbolic calculations, symbolic variables must be declared using the syms command.

syms x y

Here:

  • x and y become symbolic variables
  • MATLAB now treats them as mathematical symbols instead of numeric values

Solving Equations

MATLAB can solve algebraic equations symbolically using the solve() function.

syms x

eqn = x^2 + 5*x + 6 == 0;

S = solve(eqn, x);

In this example:

  • syms x declares a symbolic variable
  • eqn stores the equation
  • solve() finds the roots of the equation

Output:

S =

    -2
    -3

MATLAB automatically calculates the exact symbolic solutions.

Solving Systems of Equations

Multiple equations can also be solved simultaneously.

syms x y

eq1 = x + y == 10;

eq2 = x - y == 2;

sol = solve([eq1, eq2], [x, y])

This solves both equations together and returns values for x and y.

Symbolic Expressions

Symbolic expressions can be created and manipulated just like algebraic formulas.

syms x

expr = x^2 + 3*x + 2

factor(expr)

expand((x + 1)*(x + 2))

Here:

  • factor() converts expressions into factors
  • expand() multiplies and expands expressions

Differentiation

Symbolic Math can calculate derivatives automatically using the diff() function.

syms x

f = x^3 + 2*x^2 + x

diff(f)

Output:

3*x^2 + 4*x + 1

Differentiation is commonly used in optimization, physics, and machine learning.

Higher-Order Derivatives

MATLAB can calculate second, third, or higher-order derivatives.

diff(f, 2)

The second argument specifies the derivative order.

Integration

Symbolic integration calculates exact integrals mathematically.

syms x

f = x^2

int(f)

Output:

x^3/3

Definite Integrals

MATLAB can also evaluate integrals over a specific interval.

int(f, 0, 5)

This calculates the integral of f from 0 to 5.

Limits

Limits are important in calculus and mathematical analysis.

syms x

limit(sin(x)/x, x, 0)

MATLAB evaluates the symbolic limit automatically.

Substituting Values

Symbolic variables can be replaced with numeric values using subs().

syms x

expr = x^2 + 3*x

subs(expr, x, 5)

Output:

40

Converting Symbolic to Numeric

Sometimes symbolic results need to be converted into decimal values.

vpa(pi, 10)

The vpa() function provides high-precision numerical approximations.

Plotting Symbolic Functions

Symbolic functions can be visualized using MATLAB plotting functions.

syms x

fplot(x^2)

This generates the graph of the symbolic function.

Applications of Symbolic Math

  • Engineering calculations
  • Physics simulations
  • Machine learning mathematics
  • Robotics and control systems
  • Optimization problems
  • Scientific research

Advantages of Symbolic Computation

  • Provides exact mathematical solutions
  • Reduces manual calculations
  • Handles complex algebra efficiently
  • Supports advanced calculus operations
  • Useful for academic and scientific work

Best Practices

  • Declare symbolic variables clearly
  • Use symbolic math for exact calculations
  • Convert symbolic values to numeric only when necessary
  • Keep expressions readable and organized
  • Use comments for complex equations

Summary

In this lecture, we learned how MATLAB performs symbolic mathematical computations using symbolic variables and functions.

We explored solving equations, symbolic expressions, differentiation, integration, limits, substitution, and plotting symbolic functions.

Symbolic Math is a powerful feature that makes MATLAB highly effective for advanced mathematical and scientific computing tasks.

Lecture 10 Β· Advanced

Programming Structures

Advanced ~50 min

Programming structures in MATLAB help developers organize, manage, and process complex data efficiently. They are essential for building scalable applications, scientific simulations, machine learning systems, and engineering projects.

MATLAB provides advanced data structures such as Cell Arrays and Structures (Structs) that allow different types of data to be stored together in an organized way.

Introduction to Cell Arrays

A Cell Array is a special type of array that can store multiple data types inside a single container. Unlike regular arrays, cell arrays are not limited to storing only one type of data.

Cell arrays can contain:

  • Numbers
  • Strings
  • Matrices
  • Functions
  • Other arrays

Cell Arrays & Structs

C = {1, 'text', magic(3)};

S.name = 'Project';
S.value = 100;

In this example:

  • C is a cell array containing different data types
  • 1 is a numeric value
  • 'text' is a string
  • magic(3) creates a 3Γ—3 magic matrix
  • S is a structure containing fields

Accessing Cell Array Elements

Cell arrays use curly braces {} for accessing actual values.

C = {10, 'MATLAB', [1 2 3]};

C{1}

C{2}

Output:

10

MATLAB

Here:

  • C{1} accesses the first element
  • C{2} accesses the second element

Difference Between () and {}

MATLAB uses both parentheses and curly braces with cell arrays, but they behave differently.

  • () returns a cell container
  • {} returns the actual stored value
C = {5, 10};

C(1)

C{1}

Adding Data to Cell Arrays

New elements can be added dynamically to cell arrays.

C = {1, 2};

C{3} = 'New Data'

MATLAB automatically expands the cell array when new elements are added.

Introduction to Structures

Structures (Structs) store data using named fields. They are similar to objects or records in other programming languages.

Structures are useful for organizing related information together.

Creating Structures

student.name = 'Ali';

student.age = 21;

student.grade = 90;

Here:

  • student is the structure name
  • name, age, and grade are fields

Accessing Structure Fields

Structure fields are accessed using dot notation.

student.name

student.grade

Output:

Ali

90

Structure Arrays

MATLAB allows multiple structures to be grouped together into structure arrays.

students(1).name = 'Ahmed';
students(1).grade = 88;

students(2).name = 'Sara';
students(2).grade = 95;

This creates a collection of structured records.

Nested Structures

Structures can contain other structures for hierarchical data organization.

company.name = 'TechSoft';

company.manager.name = 'John';

company.manager.age = 40;

Nested structures are commonly used in complex applications and APIs.

Using fieldnames()

The fieldnames() function returns all field names inside a structure.

fieldnames(student)

This is useful for dynamic structure processing.

Combining Structures and Cell Arrays

Cell arrays and structures can work together to create flexible data models.

data.users = {
    'Ali',
    'Sara',
    'John'
};

This combines structured fields with dynamic cell storage.

Applications of Programming Structures

  • Machine learning datasets
  • Engineering simulations
  • Scientific computing
  • Database-like records
  • API response handling
  • Configuration systems

Advantages of Cell Arrays & Structs

  • Store mixed data types efficiently
  • Improve data organization
  • Support complex hierarchical data
  • Provide flexible data storage
  • Useful for real-world applications

Best Practices

  • Use structures for related grouped data
  • Use cell arrays for mixed data types
  • Choose meaningful field names
  • Avoid overly complex nesting
  • Keep data structures organized and readable

Summary

In this lecture, we learned about advanced programming structures in MATLAB including Cell Arrays and Structures.

We explored how to create, access, and manage mixed data types using cell arrays and how to organize structured information using structs.

These programming structures are essential for handling complex datasets and building scalable MATLAB applications.

Lecture 11 Β· Advanced

Simulink & App Designer

Advanced ~60 min

Introduction to graphical programming and building interactive apps within MATLAB.

Lecture 12 Β· Capstone

Capstone: Engineering Analysis

Advanced ~120 min

Process a large dataset of sensor readings, filter noise, and generate a multi-panel visualization report.

% Project steps:
% 1. Import raw sensor data
% 2. Apply a moving average filter
% 3. Compute statistical metrics
% 4. Export findings to a PDF report
Lecture 13 Β· Advanced

Signal Processing & Image Analysis

Intermediate ~55 min Requires: Lecture 12

Content coming soon...

Lecture 14 Β· Professional

Final Project β€” Engineering Simulation

Advanced ~90 min Requires: All Previous

Content coming soon...