and Simulink
Presented by:
Ravikiran B. A.
Asst. Professor, Dept of ECE
KSSEM
Introduction to MATLAB and Simulink
What is MATLAB®?
• “The Language of Technical Computing”
• Numerical Programming Environment
• MATLAB - MATrix LABoratory
• High-Level Interpreted Language
• Uses:
• Analyze Data
• Develop Algorithms
• Create Models and Applications.
• Multidisciplinary Applications
• Current Directory
• View folders and m-files
• Workspace
• View program variables
• Double click on a variable
to see it in the Array Editor
• Command History
• View Past Commands
• Save a whole session
using Diary
Array Declaration
• Unlike C, MATLAB is an interpreted language. So, there is no
need for Type Declaration.
• A single variable is interpreted as 1x1 matrix.
>> a = 5
a=
5
• Arrays are represented as a series of numbers (or characters)
within square brackets, with or without a comma separating the
values.
>> b = [1 2 3 4 5] % Percentage Symbol indicates Comment
b=
1 2 3 4 5
Multidimensional Arrays
• 2-D or Multidimensional Arrays are represented within square
brackets, with the ; (semicolon) operator indicating end of a
row.
>> c = [1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12]
c=
1 2 3
4 5 6
7 8 9
10 11 12
• c is now a 2-D array with 4 rows and 3 columns
Note : Variable names are case sensitive and can be upto 31 characters long, and have
to start with an alphabet.
K. S. School of Engineering and Management 12
Introduction to MATLAB and Simulink
Strings
• Character strings are treated as arrays too.
>> name = 'Ravi’
is the same as
>> name = [‘R’ ‘a’ ‘v’ ‘i’]
And gives the output:
name =
Ravi
Array Indices
• Unlike in case of C, MATLAB array indices start from 1.
>> d = [1 2 3 ; 4 5 6]
d=
1 2 3
4 5 6
• Addressing an element of the array is done by invoking the
element’s row and column number.
• In order to fetch the value of an element in the 2nd row and 3rd
column, we use:
>> e = d(2,3)
e=
6
K. S. School of Engineering and Management 14
Introduction to MATLAB and Simulink
Generating Matrices
• In some cases, we need to generate large matrices, which is difficult
to generate manually.
• There are plenty of built-in commands for this purpose!
• >> i = 0:10 % Generate numbers from 0 to 10 (Integers)
i=
0 1 2 3 4 5 6 7 8 9 10
Generating Matrices
• >> l = ones(3,2) %Generate a 3x2 matrix populated with 1s
l=
1 1
1 1
1 1
>> x = linspace(0,1,7)
x=
0 0.1667 0.3333 0.5000 0.6667 0.8333 1.0000
>> x = logspace(0,1,7)
x=
1.0000 1.4678 2.1544 3.1623 4.6416 6.8129 10.0000
Matrix Operations
• Operations upon Matrices can be of two types:
• Element-wise Operation
• Matrix-wise Operation
Matrix Operations
• By default, the Operators perform Matrix-wise operations.
• During Matrix-wise operations, care must be taken to avoid
dimension mismatch, specially with exponentiation, division
and multiplication.
• In case of scalar + matrix operations, matrix-wise operations are
equivalent to element-wise operations.
• ie.
Scalar + Matrix = [Scalar + Matrix(i,j)]
Scalar * Matrix = [Scalar * Matrix(i,j)]
• A dot operator(.) preceding the operator indicates Element-wise
operations.
Examples
• Let a = [2 5; 8 1]; % 2 x 2 Matrix
b = [1 2 3; 4 5 6]; % 2 x 3 Matrix
c = [1 3; 5 2; 4 6]; % 3 x 2 Matrix
• Matrix Addition (or Subtraction):
>> y = b+c' % b and c have different dimensions.
y=
2 5 8
6 9 12
• Complement:
>> d = c' % d is now a 2x3 matrix
d=
1 5 4
3 2 6
K. S. School of Engineering and Management 22
Introduction to MATLAB and Simulink
Multiplication
• Matrix Multiplication (Or Division):
>> x = b*c % b(2x3) * c(3x2) = y (2x2). No dimension mismatch
x=
23 25
53 58
• In case of element-wise multiplication, the corresponding
elements get multiplied (Matrix Dimensions must agree)
Exponentiation
• Element-wise Exponentiation is NOT the same as Matrix-wide
exponentiation.
• Matrix Exponentiation needs square matrix as input.
>> a^2 % Matrix Exponentiation: ans = a * a
ans =
44 20
32 44
Matrix Concatenation
• Matrices can be concatenated just like elements in a matrix.
• Row-wise concatenation ( separated by space or commas)
>> f = [b d]
f=
1 2 3 1 5 4
4 5 6 3 2 6
• Column-wise concatenation (separated by semicolon)
>> g = [b ; d]
g=
1 2 3
4 5 6
1 5 4
3 2 6
MATLAB Graphics
• MATLAB provides a wide variety of graphics to visualize data.
• Graphics have Interactive tools to manipulate and extract
information from them.
• Graphs can be saved, printed and downloaded in different image
formats for use elsewhere.
• MATLAB is capable of:
• 2-D plots (Line, bar, area, Pie, histogram, stem, scatter plots, etc)
• 3-D plots (Contour, surf, mesh, etc)
• Image Processing (Histogram, Image display,etc)
• Polar plots (Polar and Compass plots)
• Vector plots (Feather and Compass plots)
2-D plots
• plot(xdata_1, ydata_1, ‘LineSpec_1’,..,
xdata_n,ydata_n,’LineSpec_n’);
• xdata – Independent variable
• ydata – Dependent Variable(s)
• LineSpec –Line attributes (Marker Symbol, color, line style,
etc)
• Care must be taken to ensure that xdata and ydata have the same
dimensions (no. of columns).
• If ydata has multiple rows, each row’s data will be overlaid on
the graph.
Edit Plot
Zoom
In/Out
Pan
Insert
Control
Legend
Rotate
Insert
Data Colorbar
Cursor
• xlabel is used to label the X-axis, and ylabel is used to label the Y-
axis.
• LATEX conventions can be used here as well.
• \ for special characters, ^ for superscript and _ for subscript,
etc.
Logarithmic Scales
• Plot command plots values in linear scale.
• In case we need to plot values in logarithmic scale we use:
semilogx(x,y) – Where only X-axis is in logarithmic scale
semilogy(x,y) – Where only Y-axis is in logarithmic scale
loglog(x,y) – Where both X and Y axes are in logarithmic scale
Problem
• Given:
T = 0:1e-5:2e-3 % Time base
Fc = 1e4; fm = 2e3 % Signal Frequencies
Vm = 3V; Vc =5V % Signal Voltages
Wm = 2 π fm; Wc = 2 π fc % Angular Frequencies
3-D Plots
• MATLAB also supports 3-D plots (x,y,z).
x = 0 : pi/50 : 10*pi;
y = sin(x);
z = cos(x);
plot3(x,y,z)
grid on;
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2);
Z = sin(R)./R; %Sinc function
%Mesh Plot
subplot(2,1,1);
mesh(X,Y,Z);
% Surface Plot
subplot(2,1,2);
surf(X,Y,Z);
Contour plots
• contour function generates a 2-D contour map, from 3-D space.
• Contours are color-mapped projection of 3-D surfaces onto 2-D
space.
• Example:
[X,Y,Z] = peaks(25);
figure(1);
subplot(2,1,1);
surf(X,Y,Z);
subplot(2,1,2);
contour(X,Y,Z);
Operators
• MATLAB allows the use of relational and logical operators
such as:
• == Equal To
• ~= Not Equal To
• < Smaller Than
• > Greater Than
• <= Lesser Than or Equal To
• >= Greater Than or Equal To
• & Logical AND
• | Logical OR
Flow Control
• Just like in C-language, MATLAB allows for some flow control
statements like:
• If-else
• For
• While
• Break
• …
or
Syntax: Example:
MATLAB Scripts
• Scripts are programs written for interpreters (as opposed to
compilers)
• Scripts automate execution of tasks for a particular application.
• MATLAB scripts are based on C-language syntax
• % symbol is used for single line comments.
• MATLAB does not support multiline commenting.
• MATLAB scripts can be divided into independently-executable
sections using the %% symbol (Section Breaks). This is very
useful for larger programs with multiple sections.
• Scripts are stored with a .m file extension.
A Simple Script
MATLAB Functions
• Whenever we have huge programs, with repeated operations, it
is preferable to use functions.
• Functions make code more readable and compact.
• Functions speed up processing, and simplify the code.
• MATLAB functions are indicated by a keyword function, and
can handle multiple variables.
• MATLAB Functions are of three types:
• Inline Functions
• Anonymous Functions
• Standalone Functions
Inline Functions
• Inline Functions accept (usually numerical) input and return
output.
• Function evaluation takes place in the current workspace.
• Keyword used : inline
• Example : Consider a function where I need to evaluate Cosine
Law: 𝑐 = 𝑎2 + 𝑏 2 − 2𝑎𝑏 𝑐𝑜𝑠𝜃
>> cval = inline('sqrt(a^2+b^2-2*a*b*cos(theta))');
>> d = cval(2, 3, pi/6)
d=
1.6148
Anonymous Functions
• An anonymous function is a function that is not stored in a
program file, but is associated with a variable whose data type
is function_handle.
• Can contain only a single executable statement.
• Faster than inline functions.
• Example : Evaluate Cosine Law (as earlier)
Function Files
• Commands executed in a separate workspace which is created
whenever the function is called.
• Function files are saved with the same name as the function,
with a .m extension.
• During function calls, input and output arguments have to be
specified.
• The first (command) line of a Function M-file MUST be a
function declaration line specifying input and ouput variables.
• Make sure that no undefined variable occurs as input to these
commands!
Problem
1. Create a function that generates the factorial of a given
number.
Import/Export
• Depending on the type of files containing the data, different
MATLAB commands can be used to import or export data.
• Data import/export can be done in two ways:
• Commands in Command Line
• Right Click and Import/Export from Workspace/Command Window
Text Files
• csvread Read comma-separated value file
• csvwrite Write comma-separated value file
• dlmread Read ASCII-delimited file of numeric data into
matrix
• dlmwrite Write matrix to ASCII-delimited file
• textscan Read formatted data from text file or string
• readtable Create table from file
• writetable Write table to file
• type Display contents of file
• Let’s try plotting the temperature variation for the past 20 years!
>>plot(TempVals);
title(['Temperature Variations from ',num2str(C{3}(1,:)), ' to ', num2str(C{3}(end,:))]);
xlabel('Days');
ylabel('Temperature (F)');
Extracting Data
• Now, let’s try plotting the daily temperatures only for July 2013.
• We need to isolate the data pertaining to July in column 1 and
2013 in column 3.
>> Indices = find(C{1}== 7 & C{3}==2013);
>> Plot(C{2}(Indices,:),C{4}(Indices,:));
.csv files
• Most databases store data in CSV format (Comma Separated
Value), where the comma is the delimiter.
• MATLAB’s csvread function makes importing CSV data easy.
• Syntax: X = csvread(‘filename.csv’, row, col);
• Here, Row and Col indicate the row and column number from
which scanning has to commence. (zero based)
• In case the CSV files have headers, titles, explanations, etc, we
can skip those lines from the files and point the (Row, Col)
values to the cell where the data begins.
• Once the import is done, X becomes a matrix of values where
data is stored.
Example
• Let us try and extract some BSE data from 1990 to 2014.
• Data is in the file bsedata.csv
• Data is in the format: Year – Open – High – Low – Close
• Since the Row 1 is just headers, we will skip that and load the
rest into a variable MarketData.
>> MarketData = csvread('bsedata.csv',1,0);
• Now, all the data is stored in MarketData. Now we can assign
them to the respective columns.
YearData = MarketData(:,1);
OpeningData = MarketData(:,2);
HighData = MarketData(:,3);
LowData = MarketData(:,4);
ClosingData = MarketData(:,5);
Exporting to Excel
• Syntax : Status = xlswrite(filename,A,sheet,xlRange)
• Filename – Name of the Excel File to be created.
• A – Matrix/Vector to be stored in the Spreadsheet
• Sheet – Sheet Number in the workbook
• xlRange – Range of cells in which data is to be stored.
• Status – 1 if successful, 0 in case of failure.
Problem
• Get the spreadsheet file : Monthly_And_Annual_Rainfall.xls
• Extract data into the workspace.
• Plot the annual rainfall values for any 5 cities from 1951 to
2012, clearly indicating the cities.
• Plot the seasonal rainfall for the same 5 cities for the year 1980
in another graph.
Acknowledgment
• MathWorks®, MATLAB®, Simulink® and the Mathworks Logo
are all trademarks or registered trademarks of The MathWorks,
Inc.