MATLAB Training Notes
Introductory Sessions of MATLAB Training Course
Why MATLAB?
MATLAB (MATrix LABoratory) is a high-level language and interactive environment used
for numerical computation, visualization, and programming. Its rich set of toolboxes makes it
ideal for a variety of applications in engineering, science, and economics.
Real-life Applications:
Engineers use MATLAB for system design and simulation.
Scientists use it for data analysis and visualization.
Economists use it for financial modeling and analysis.
What Are Toolboxes?
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems.
Example:
Signal Processing Toolbox
Image Processing Toolbox
MATLAB Interface
The MATLAB interface consists of various components like the Command Window,
Workspace, Command History, and Editor.
Command Window:
Used to enter commands and see results.
Editor:
Used to write, edit, and run MATLAB scripts and functions.
Workspace:
Shows variables that you create or import during a session.
Command History:
Logs the commands that you run.
Introduction to Arrays and Matrices
MATLAB is built around the concept of matrices. Everything in MATLAB is a matrix or an
array, which is a collection of numbers arranged into rows and columns.
Example Code:
matlab
Copy code
% Creating a matrix
A = [1 2 3; 4 5 6; 7 8 9];
% Accessing elements
element = A(2, 3); % Element at 2nd row, 3rd column
Real-life Applications:
Data representation in finance and engineering.
Image representation in image processing.
MATLAB File Types
.m files: Scripts and functions.
.mat files: Binary files for storing variables.
.fig files: MATLAB figure files.
Example Code:
matlab
Copy code
% Saving variables
save('data.mat', 'A');
% Loading variables
load('data.mat');
Basics of MATLAB Programming
Includes basic programming constructs such as variables, arrays, functions, and control flow.
Handling Data and Data Flow in MATLAB
Data Types
MATLAB supports various data types such as double, char, logical, cell, and structure arrays.
Example Code:
matlab
Copy code
% Different data types
a = 10; % Double
b = 'hello'; % Character array (string)
c = true; % Logical
d = {1, 2, 3}; % Cell array
e = struct('field1', 1, 'field2', 'value'); % Structure
Creating Variables
Variables are created by simply assigning a value to them.
Example Code:
matlab
Copy code
% Creating variables
x = 5;
y = [1 2 3 4 5];
Scalars, Vectors, and Matrix Operations & Operators
Scalar: A single number.
Vector: A one-dimensional array.
Matrix: A two-dimensional array.
Example Code:
matlab
Copy code
% Scalar
a = 5;
% Vector
b = [1 2 3];
% Matrix
c = [1 2; 3 4];
% Operations
result = a + b; % Scalar addition to a vector
result = b * c; % Vector-matrix multiplication
Real-life Applications:
Computational mathematics in scientific research.
Matrix operations in computer graphics.
Importing & Exporting of Data
Data can be imported from and exported to various formats such as text files, spreadsheets,
and binary files.
Example Code:
matlab
Copy code
% Importing data
data = readmatrix('data.csv');
% Exporting data
writematrix(data, 'output.csv');
File Editing and Debugging in MATLAB
Writing Script Files
Scripts are files containing a sequence of MATLAB commands. They operate on data in the
workspace.
Example Script (script.m):
matlab
Copy code
% Script file example
x = 1:10;
y = x.^2;
plot(x, y);
Writing Function Files
Functions are files that take input arguments and return output arguments. They have their
own workspace.
Example Function (myFunction.m):
matlab
Copy code
function result = myFunction(a, b)
result = a + b;
end
Inserting Breakpoints and Debugging
Breakpoints are used to pause the execution of a script or function to examine the workspace.
Example Code:
matlab
Copy code
% Insert a breakpoint
dbstop in script.m at 2
% Run the script
script
Error Correction
MATLAB provides various ways to handle and correct errors, including try-catch blocks.
Example Code:
matlab
Copy code
try
% Code that might cause an error
result = myFunction(a, b);
catch ME
% Handle the error
disp(ME.message);
end
MATLAB Graphics I
Simple Graphics & Types
MATLAB can generate various types of plots such as line, bar, and scatter plots.
Example Code:
matlab
Copy code
% Line plot
x = 1:10;
y = x.^2;
plot(x, y);
% Bar plot
bar(x, y);
% Scatter plot
scatter(x, y);
Plotting Functions
Functions like plot, bar, and scatter are used for plotting data.
Example Code:
matlab
Copy code
% Plotting a sine wave
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);
Creating and Editing Plots (2D & 3D)
MATLAB allows creating and customizing plots.
Example Code:
matlab
Copy code
% 2D plot
plot(x, y);
title('Sine Wave');
xlabel('x-axis');
ylabel('y-axis');
% 3D plot
z = cos(x);
plot3(x, y, z);
title('3D Plot');
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
MATLAB Programming I
Conditional Statements
if, else, and elseif statements are used for conditional execution of code.
Example Code:
matlab
Copy code
x = 10;
if x > 0
disp('x is positive');
elseif x < 0
disp('x is negative');
else
disp('x is zero');
end
Iterative Statements
Loops like for and while are used for repetitive tasks.
Example Code:
matlab
Copy code
% For loop
for i = 1:10
disp(i);
end
% While loop
i = 1;
while i <= 10
disp(i);
i = i + 1;
end
Flow Control
MATLAB supports flow control using break, continue, and return statements.
Example Code:
matlab
Copy code
for i = 1:10
if i == 5
continue; % Skip the rest of the code in the loop
end
disp(i);
end
Efficient Coding Practices
Efficient coding practices include preallocating arrays and avoiding loops when possible.
Example Code:
matlab
Copy code
% Preallocating arrays
n = 1000;
A = zeros(n, 1);
% Avoiding loops
A = rand(1, n);
B = A + 1; % Vectorized operation
Linear Algebra
MATLAB provides functions for various linear algebra operations.
Example Code:
matlab
Copy code
% Matrix multiplication
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A * B;
% Solving linear equations
A = [1 1; 1 2];
b = [2; 3];
x = A\b;
Real-life Applications:
Solving systems of linear equations in engineering.
Eigenvalue problems in physics.
Polynomials
MATLAB can handle polynomial operations such as finding roots and evaluating
polynomials.
Example Code:
matlab
Copy code
% Define a polynomial
p = [1 -3 2]; % Represents x^2 - 3x + 2
% Find roots
r = roots(p);
% Evaluate polynomial
x = 1:10;
y = polyval(p, x);
Curve Fitting
MATLAB provides tools for fitting curves to data.
Example Code:
matlab
Copy code
% Data
x = 1:10;
y = [2.1, 2.5, 3.6, 4.5, 5.9, 7.2, 8.5, 9.1, 10.2, 11.3];
% Fit a polynomial
p = polyfit(x, y, 2);
% Evaluate the fit
y_fit = polyval(p, x);
plot(x, y, 'o', x, y_fit, '-');
Real-life Applications:
Data analysis in scientific research.
Trend analysis in finance.
Differentiation & Integration
MATLAB provides functions for numerical differentiation and integration.
Example Code:
matlab
Copy code
% Differentiation
syms x;
f = x^2 + 3*x + 2;
df = diff(f);
% Integration
int_f = int(f);
% Numerical integration
y = sin(x);
integral_value = integral(@(x) sin(x), 0, pi);
Real-life Applications:
Calculating areas under curves in physics.
Solving differential equations in engineering.
MATLAB Graphics II
Introduction to Graphical User Interfaces (GUI)
GUIs in MATLAB allow users to create interactive applications.
GUI Tools:
Guide: A tool for creating GUIs.
App Designer: A more modern tool for creating apps.
Creating Functioning GUIs
Example Code:
matlab
Copy code
% Simple GUI using App Designer
app = uifigure;
btn = uibutton(app, 'push', 'ButtonPushedFcn', @(btn,event) disp('Button
pushed!'));
MATLAB Programming II
Probability & Statistics
MATLAB provides functions for statistical analysis and probability distributions.
Example Code:
matlab
Copy code
% Mean and standard deviation
data = [1, 2, 3, 4, 5];
mean_value = mean(data);
std_value = std(data);
% Probability distributions
pd = makedist('Normal');
random_numbers = random(pd, 1, 1000);
Real-life Applications:
Data analysis in social sciences.
Risk assessment in finance.
Cells & Structures
Cells and structures are used for storing heterogeneous data.
Example Code:
matlab
Copy code
% Cell array
c = {1, 'text', [3, 4, 5]};
% Structure array
s = struct('field1', 1, 'field2', 'text');
Performance Measures
MATLAB provides tools to measure and improve code performance.
Example Code:
matlab
Copy code
% Measure execution time
tic;
pause(1);
elapsedTime = toc;
Introduction to Symbolic Math
MATLAB supports symbolic computations using the Symbolic Math Toolbox.
Example Code:
matlab
Copy code
% Symbolic variables
syms x y;
f = x^2 + y^2;
MATLAB Toolboxes
Data Acquisition Toolbox
Used for collecting data from external devices like sensors.
Example Code:
matlab
Copy code
% Acquire data from a device
ai = analoginput('nidaq', 'Dev1');
addchannel(ai, 0);
start(ai);
data = getdata(ai);
Signal Processing Toolbox
Provides tools for analyzing and processing signals.
Example Code:
matlab
Copy code
% Signal analysis
t = 0:0.001:1;
x = sin(2*pi*50*t) + sin(2*pi*120*t);
y = fft(x);
Image Acquisition Toolbox
Used for acquiring images from cameras and other imaging devices.
Example Code:
matlab
Copy code
% Acquire image
vid = videoinput('winvideo', 1);
start(vid);
img = getsnapshot(vid);
imshow(img);
Image Processing Toolbox
Provides tools for image processing tasks.
Example Code:
matlab
Copy code
% Read and display an image
img = imread('peppers.png');
imshow(img);
% Image enhancement
img_enhanced = imadjust(img);
imshow(img_enhanced);
Introduction to SIMULINK
What is SIMULINK?
SIMULINK is a block diagram environment for multi-domain simulation and Model-Based
Design.
Example:
Simulating dynamic systems in automotive engineering.
Designing control systems in aerospace.
SIMULINK Interface
The interface includes the Library Browser, where you can find blocks to build models, and
the Model window, where you assemble your system.
Libraries & Tools
SIMULINK provides a wide range of libraries for different types of systems and applications.
Example Code:
matlab
Copy code
% Create a new model
new_system('myModel');
% Open the model
open_system('myModel');
% Add a block
add_block('simulink/Commonly Used Blocks/Sine Wave', 'myModel/SineWave');
Conclusion
MATLAB is a versatile and powerful tool used across various industries for numerical
computation, data analysis, and simulation. Mastery of MATLAB can significantly enhance
your ability to solve complex problems and create sophisticated models and simulations.