SlideShare a Scribd company logo
Introduction to Matlab
by
Mr. M. Ravi,
Asst. Professor,
Dept, of E.C.E.
What is Matlab?
• Matlab is basically a high level language which has
many specialized toolboxes for making things easier
for us
Assembly
High Level
Languages such as
C, Pascal etc.
Matlab
What are we interested in?
• Matlab is too broad for our purposes in this course.
• The features we are going to require is
Matlab
Command
Line
m-files
functions
mat-files
Command execution
like DOS command
window
Series of
Matlab
commands
Input
Output
capability
Data
storage/
loading
Physical Problem
Mathematical Models
Solving Mathematical Equations
Introduction
• MATLAB (short for MATrix LABoratory) is a powerful computing
environment that handles anything from simple arithmetic to
advanced data analysis.
• At its core is the matrix as its basic data type.
• Combined with extensive maths and graphics functions,
complicated calculations can be carried out by specifying only a
few simple instructions.
• MATLAB can be used to do anything your scientific calculator
can do, and more.
• The installations in the computer labs include tool boxes that
include functions for electrical engineering related tasks, such
as signal processing and system analysis.
Introduction. . . .
• You can plot your data in a multitude of visualizations as well.
• Computations can be carried out in one of three ways:
1. Directly from the command line,
2. by writing a script that carries out predefined instructions, or
3. by writing your own functions.
Introduction . . .
• Writing your own functions is much like programming in
other languages, except that you have the full resources of
MATLAB’s functions at your disposal, making for very
compact code.
The MATLAB-6 and above environment has several windows
at your disposal.
• Command Window: The main window is the command window,
where you will type all your commands, for small programs.
Desktop Tools
• Command Window
– type commands
• Workspace
– view program variables
– Clear/clear all is used to clear the workspace window
– double click on a variable to see it in the Array Editor
• Command History
– view past commands
– save a whole session using diary
• Editor Window
To write a program
• Current Directory Window
Matlab Tutorial.ppt
Matlab Screen
• Command Window
– type commands
• 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
Command History
* A command history, which contains a list of all the
commands that you have typed in the command
window.
* This makes it easy to cut and paste earlier lengthy
commands, saving you the effort of typing it over
again.
* This window can also display the contents of the
current directory.
Workspace
• The third window displays one of two things:
* The launch pad from which you can browse the
installed toolboxes and launch various tools as
well as view demonstrations, and
* The workspace, which lists all the variables that
are currently in memory as well as their sizes.
The Toolbar
Vectors and Matices and their
Manipulation
Definition of Vectors & Matrices
• MATLAB is based on matrix and vector algebra; even
scalars are treated as 1x1 matrices. Therefore, vector and
matrix operations are as simple as common calculator
operations.
• Vectors can be defined in two ways.
* The first method is used for arbitrary elements:
v = [1 3 5 7]; creates a 1x4 vector with elements 1, 3, 5
and 7.
* Note that commas could have been used in place of spaces
to separate the elements. that is v=[1,3,5,7];
• Additional elements can be added to the vector: v(5) = 8;
yields the vector v = [1 3 5 7 8].
• Previously defined vectors can be used to define a new
vector. For example, with ‘v’ defined above
a = [9 10];
b = [v a];
creates the vector b = [1 3 5 7 8 9 10].
Second Method
• The second method is used for creating vectors with
equally spaced elements:
t = 0: 0.1:10;
creates a 1x101 vector with the elements 0, .1, .2,
.3,...,10. Note that the middle number defines the
increment.
• If only two numbers are given, then the
increment is set to a default of 1:
For ex. k = 0:10; creates a 1x11 vector with the
elements 0, 1, 2, ..., 10.
* Matrices are defined by entering the elements row by row:
M = [1 2 4; 3 6 8; 2 6 5];
creates the matrix
* Transpose of M is denoted by
M’, and displays as
*The inverse of M is M-1 denoted in
Matlab as M^-1and displays as
* M(2,3) displays the
element of second
row and third column
Arithmetic Operations
• When applying addition, subtraction, multiplication and division
between a scalar (that is a single number) and a vector we use
+, -, *, and / respectively.
Let
Then a + b gives
a - b gives
aXb in Matlab a*b displays
In Matlab a.*b gives element wise multiplication
a+2 gives
Algebraic manipulations
• Scalar Calculations. The common arithmetic operators used in
spreadsheets and program-ming languages such as BASIC are used in
‘Matlab'.
• In addition a distinction is made between right and left division. The
arithmetic operators are
Operators (relational, logical)
= = equal
~= not equal
< less than
<= less than or equal
> greater than
>= greater than or equal
& AND
| OR
~ NOT
1

pi 3.14159265…
j imaginary unit,
i same as j
Special Matrices
• null matrix:
M = [ ];
• nxm matrix of zeros:
M = zeros(n,m);
nxm matrix of ones:
M = ones(n,m);
nxn identity matrix:
M = eye(n);
Help, Document and Demos
• Matlab provides excellent tutorials that are accessible by typing
>>demo
• The Basic matrix operations tutorial under the Matrices tutorial, the
Image Processing and Signal Processing tutorial under Toolboxes
are highly recommended.
• To get information on a particular function of Matlab, we type
>>help function_name
Example:
>> help fft
>> help mean
Getting Help
The Help pull-down menu gives you access to all the help pages
included with MATLAB.
• Comments in Matlab must be proceeded by %
% This is a comment in Matlab.
• To define a function in Matlab, we first create a function with the
name of the function.
*We then define the function in the file.
*For example, the Matlab documentation recommends stat.m written as:
function [mean,stdev] = stat(x)
% This comment is printed out with help stat
n = length(x); % assumes that x is a vector.
mean = sum(x) / n; % sum adds up all elements.
stdev = sqrt(sum((x - mean).^2)/n);
Viewing Matlab Matrices as one Dimensional Arrays
• Convert multi-dimensional to a one-dimensional array by simply using
array_name(:)
» a(:)
ans =
1
4
7
2
5
8
3
6
9
Note that the elements in the one-dimensional array are arranged column by column,
not row by row. This is the same convention that is used for two dimensional arrays
in Fortran, and this will also be the convention that we will adopt for representing
two dimensional arrays in C++.
Displaying and Printing in Matlab
• To plot an array or display an image, select the
figure using:
» figure(1); % select the figure to display.
» clf % clear the figure from any
% previous commands.
• and use plot for displaying a one-dimen-sional array:
» plot ([3 4 5 3 2 2]); % plots broken-line graph.
• or use imagesc for displaying a two dimensional
array (image):
One-dimensional random access iterator
(using an index array)
[1 5 9 2 6 10 3 7 11 4 8 12]
» I=[1 5 8 10]; % indices apply to one-dimensional array a(:)
» a(I)
ans =
1 6 7 4
– two dimensional iterators
» a(1:2,1:3)
ans = 1 2 3
5 6 7 .
Working with Memory in Matlab
• To keep track of how memory is allocated, we use whos
» b=[34 54 56];
» a=[2 3 56];
» whos
Name Size Bytes Class
a 1x3 24 double array
b 1x3 24 double array
Grand total is 6 elements using 48 bytes
We may then get rid of unwanted variables using clear
» clear a; % removes the variable a from the memory.
• We can use clear all to remove all variables from memory (and all
functions and mex links) and close all to close all the figures and
hence save a lot of memory.
• Since Matlab supports dynamic memory allocation, it is possible
to make inefficient use of the memory due to memory
fragmentation problems. In this case, the pack command can be
used to defragment the memory and help reclaim some of the
memory.
• To use memory efficiently, it is best to avoid changing the number
of elements in an array during execution. It is best to
• preallocate arrays before using them. To this end we can use zeros
and ones:
» a=zeros(3,4); % a two-dimensional 3x4 zero matrix.
» b=ones(1,5); % an array of 5 elements of value 1.
Evaluating one-dimensional
functions in Matlab
• To evaluate one-dimensional functions in Matlab we need to
specify the points at which we would like our function to be
evaluated at.
• We can use either the built-in colon notation to specify the
points » t=-1:0.5:1
t = -1.0000 -0.5000 0 0.5000 1.0000
or use linspace( )
» t=linspace(-2,4,5) % generates 5 points
% between -2 and 4
t = -2.0000 -0.5000 1.0000 2.5000 4.0000
or use logspace( )
Evaluating one-dimensional functions in Matlab
(contd)
• In general, all numbers in Matlab are double. Complex
numbers are represented by multiplying the imaginary part
by 1i. For example, 1+3j can be represented by 1+1i*3 or
1+3i.
• All the well-known mathematical functions are defined in
Matlab, and but they apply to to each element in the vector
directly.
• For example, cos([2 3 4]) is equivalent to [cos(2) cos(3)
cos(4)].
Evaluating two-dimensional
functions in Matlab
• To evaluate two-dimensional functions in Matlab we use the
built-in function meshgrid ( ) with the ranges for x and y;
eg:
» [x,y]=meshgrid(0.1:0.1:0.3, 0.2:0.1:0.4)
yields the matrices x and y given by:
x =
0.1 0.2 0.3
0.1 0.2 0.3
0.1 0.2 0.3
y =
0.2 0.2 0.2
0.3 0.3 0.3
0.4 0.4 0.4
• We may then apply any binary operation to x and y provided that we
preceed each operation with a period.
• For example x.*y represents the matrix where each element of x
multiplies each element of y.
• Similarly, exp(x.^2+y.^2) represents the matrix resulting from
applying exp( ) to the sum of the squares of each of the elements of x
and y.
Flow Control
• if
• for
• while
• break
• ….
Control Structures
• If Statement Syntax
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
Some Dummy Examples
if ((a>3) & (b==5))
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end
Control Structures
• For loop syntax
for i=Index_Array
Matlab Commands
end
Some Dummy Examples
for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
Control Structures
• While Loop Syntax
while (condition)
Matlab Commands
end
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
Generation and plotting of basic
signals
Simple plot
To make a graph of y = sin(t) on the interval t = 0 to t = 10
we do the following:
>> t = 0:0.3:10;
>> y = sin(t);
>> plot(t,y) ;
Matlab Graphics
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
Multiple Plots
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)
• Second, I can plot several different sets of data together:
>> x = 0 : 0.1 : 10;
>> y = sin(x);
>> z = cos(x);
>> plot(x, y, x, z);
• Another useful command is axis, which lets you control the size of the
axes. If I've already created the plot with both sine and cosine
functions, I can resize it by typing
>> axis([-5, 15, -3, 3]);
which changes the plotting window so it looks like this:
• f (x)=sin (x)3 +cos(3x)
• over one period
syms x;
ezplot(sin(x)^3+ cos(3*x), [-pi pi], 1);
grid on;
Continuous and Discrete time plots
k=0:20;
y=binopdf(k,20,0.5);
plot(k,y)
k=0:20;
y=binopdf(k,20,0.5);
stem(k,y)
Plotting
Matlab Tutorial.ppt
Matlab Tutorial.ppt
Commonly Used Mathematical Functions
Using Matlab Editors
• Very small programs can be typed and executed in command window.
• Large programs on other hand can be used the Matlab editor.
• The complete program can be typed in the Matlab editor and saved as
‘file_name.m’, and can be retrieved when-ever necessary.
• You can execute either directly from editor window or type the file
name in the command window and press the enter button.
Creating, Saving, and Executing a Script File
% CIRCLE - A script file to draw a pretty circle
function [x, y] = prettycirclefn(r)
% CIRCLE - A script file to draw a pretty circle
% Input: r = specified radius
% Output: [x, y] = the x and y coordinates
angle = linspace(0, 2*pi, 360);
x = r * cos(angle);
y = r * sin(angle);
plot(x,y)
axis('equal')
ylabel('y')
xlabel('x')
title(['Radius r =',num2str(r)])
grid on
Graph Functions (summary)
• plot linear plot
• stem discrete plot
• grid add grid lines
• xlabel add X-axis label
• ylabel add Y-axis label
• title add graph title
• subplot divide figure window
• figure create new figure window
• pause wait for user response
• clc: clear command window
• clear all: clear all variables in workspace
window
• close all: closes all previous figure windows
Random Numbers
x=rand(100,1);
stem(x);
hist(x,100)
Thank You…
END

More Related Content

PPTX
Matlab ppt
chestialtaff
 
PPTX
Introduction to matlab lecture 1 of 4
Randa Elanwar
 
PPT
Brief Introduction to Matlab
Tariq kanher
 
PPTX
An Introduction to MATLAB for beginners
Murshida ck
 
PPT
Introduction to Matlab
aman gupta
 
PDF
MATLAB INTRODUCTION
Dr. Krishna Mohbey
 
PPTX
Matlab Introduction
ideas2ignite
 
PPT
Matlab Basic Tutorial
Muhammad Rizwan
 
Matlab ppt
chestialtaff
 
Introduction to matlab lecture 1 of 4
Randa Elanwar
 
Brief Introduction to Matlab
Tariq kanher
 
An Introduction to MATLAB for beginners
Murshida ck
 
Introduction to Matlab
aman gupta
 
MATLAB INTRODUCTION
Dr. Krishna Mohbey
 
Matlab Introduction
ideas2ignite
 
Matlab Basic Tutorial
Muhammad Rizwan
 

What's hot (20)

PPT
Matlab practical and lab session
Dr. Krishna Mohbey
 
PPSX
Introduction to MATLAB
Ashish Meshram
 
PDF
MATLAB Programming
محمدعبد الحى
 
PDF
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
PDF
Introduction to Matlab
Amr Rashed
 
PPT
Introduction to matlab
Tarun Gehlot
 
PDF
MATLAB Basics-Part1
Elaf A.Saeed
 
PPT
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
reddyprasad reddyvari
 
PPSX
Introduction to MATLAB
Bhavesh Shah
 
PDF
Introduction to matlab
Santosh V
 
PPTX
Matlab ppt
Dhammpal Ramtake
 
PDF
Latex Introduction for Beginners
ssuser9e8fa4
 
PDF
Matlab solved problems
Make Mannan
 
PPTX
What is matlab
Shah Rukh Qureshi
 
PDF
Advanced MATLAB Tutorial for Engineers & Scientists
Ray Phan
 
PPTX
Matlab introduction
Ameen San
 
PPTX
Matlab plotting
shahid sultan
 
PPT
Gamma function
Solo Hermelin
 
PPTX
Application of eigen value eigen vector to design
Home
 
PPTX
Introduction to MATLAB
Ravikiran A
 
Matlab practical and lab session
Dr. Krishna Mohbey
 
Introduction to MATLAB
Ashish Meshram
 
MATLAB Programming
محمدعبد الحى
 
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Introduction to Matlab
Amr Rashed
 
Introduction to matlab
Tarun Gehlot
 
MATLAB Basics-Part1
Elaf A.Saeed
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
reddyprasad reddyvari
 
Introduction to MATLAB
Bhavesh Shah
 
Introduction to matlab
Santosh V
 
Matlab ppt
Dhammpal Ramtake
 
Latex Introduction for Beginners
ssuser9e8fa4
 
Matlab solved problems
Make Mannan
 
What is matlab
Shah Rukh Qureshi
 
Advanced MATLAB Tutorial for Engineers & Scientists
Ray Phan
 
Matlab introduction
Ameen San
 
Matlab plotting
shahid sultan
 
Gamma function
Solo Hermelin
 
Application of eigen value eigen vector to design
Home
 
Introduction to MATLAB
Ravikiran A
 
Ad

Similar to Matlab Tutorial.ppt (20)

PDF
Matlab pt1
Austin Baird
 
PDF
Mat lab
Gizachew Kefelew
 
PPTX
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
PPT
matlab_tutorial.ppt
SudhirNayak43
 
PPT
matlab_tutorial.ppt
KrishnaChaitanya139768
 
PPT
matlab_tutorial.ppt
ManasaChevula1
 
PPT
Matlab basics
TrivediUrvi2
 
PPT
matlab tutorial with separate function description and handson learning
vishalkumarpandey12
 
PPTX
Matlab-1.pptx
aboma2hawi
 
PDF
An Introduction to MATLAB with Worked Examples
eAssessment in Practice Symposium
 
PPTX
intro2matlab-basic knowledge about Matlab.pptx
uf5221985
 
PDF
Introduction to MATLAB
Dun Automation Academy
 
PPTX
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
PPT
Matlab anilkumar
THEMASTERBLASTERSVID
 
PDF
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
PPT
Introduction to Matlab - Basic Functions
joellivz
 
PPT
MatlabIntro (1).ppt
AkashSingh728626
 
PPTX
1. Introduction to Computing - MATLAB.pptx
tgkfkj9n2k
 
PPT
Introduction_to_Matlabbanmar k ibrahim a
naghamsalimmohammed
 
Matlab pt1
Austin Baird
 
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
matlab_tutorial.ppt
SudhirNayak43
 
matlab_tutorial.ppt
KrishnaChaitanya139768
 
matlab_tutorial.ppt
ManasaChevula1
 
Matlab basics
TrivediUrvi2
 
matlab tutorial with separate function description and handson learning
vishalkumarpandey12
 
Matlab-1.pptx
aboma2hawi
 
An Introduction to MATLAB with Worked Examples
eAssessment in Practice Symposium
 
intro2matlab-basic knowledge about Matlab.pptx
uf5221985
 
Introduction to MATLAB
Dun Automation Academy
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
Matlab anilkumar
THEMASTERBLASTERSVID
 
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
Introduction to Matlab - Basic Functions
joellivz
 
MatlabIntro (1).ppt
AkashSingh728626
 
1. Introduction to Computing - MATLAB.pptx
tgkfkj9n2k
 
Introduction_to_Matlabbanmar k ibrahim a
naghamsalimmohammed
 
Ad

More from RaviMuthamala1 (9)

PPTX
29-04-2021_CS-II-EEE(A&B)SFG&MASSON'S.pptx
RaviMuthamala1
 
PPTX
26-04-2021_CS-II-EEE(A&B)BDRT.pptx
RaviMuthamala1
 
PPTX
26-04-2021_CS-II-EEE(A&B)BDRT.pptx
RaviMuthamala1
 
PPTX
03-05-2021_CS-EEE-A&B-SFG_synchros.pptx
RaviMuthamala1
 
PPTX
01-05-2021_CS-EEE-A&B-SFG_synchros.pptx
RaviMuthamala1
 
PPTX
Unit 5.pptx
RaviMuthamala1
 
PPTX
State space analysis.pptx
RaviMuthamala1
 
PPTX
Unit 1.pptx
RaviMuthamala1
 
PPT
Main project-Image compression -ppt in 2003.ppt
RaviMuthamala1
 
29-04-2021_CS-II-EEE(A&B)SFG&MASSON'S.pptx
RaviMuthamala1
 
26-04-2021_CS-II-EEE(A&B)BDRT.pptx
RaviMuthamala1
 
26-04-2021_CS-II-EEE(A&B)BDRT.pptx
RaviMuthamala1
 
03-05-2021_CS-EEE-A&B-SFG_synchros.pptx
RaviMuthamala1
 
01-05-2021_CS-EEE-A&B-SFG_synchros.pptx
RaviMuthamala1
 
Unit 5.pptx
RaviMuthamala1
 
State space analysis.pptx
RaviMuthamala1
 
Unit 1.pptx
RaviMuthamala1
 
Main project-Image compression -ppt in 2003.ppt
RaviMuthamala1
 

Recently uploaded (20)

PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PDF
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
PPTX
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
ghousebhasha2007
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PDF
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
Hyogeun Oh
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
dodultrongaming
 
PDF
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
ijcncjournal019
 
PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
Introduction to Data Science: data science process
ShivarkarSandip
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
ghousebhasha2007
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
Hyogeun Oh
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
dodultrongaming
 
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
ijcncjournal019
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 

Matlab Tutorial.ppt

  • 1. Introduction to Matlab by Mr. M. Ravi, Asst. Professor, Dept, of E.C.E.
  • 2. What is Matlab? • Matlab is basically a high level language which has many specialized toolboxes for making things easier for us Assembly High Level Languages such as C, Pascal etc. Matlab
  • 3. What are we interested in? • Matlab is too broad for our purposes in this course. • The features we are going to require is Matlab Command Line m-files functions mat-files Command execution like DOS command window Series of Matlab commands Input Output capability Data storage/ loading
  • 5. Introduction • MATLAB (short for MATrix LABoratory) is a powerful computing environment that handles anything from simple arithmetic to advanced data analysis. • At its core is the matrix as its basic data type. • Combined with extensive maths and graphics functions, complicated calculations can be carried out by specifying only a few simple instructions. • MATLAB can be used to do anything your scientific calculator can do, and more. • The installations in the computer labs include tool boxes that include functions for electrical engineering related tasks, such as signal processing and system analysis.
  • 6. Introduction. . . . • You can plot your data in a multitude of visualizations as well. • Computations can be carried out in one of three ways: 1. Directly from the command line, 2. by writing a script that carries out predefined instructions, or 3. by writing your own functions.
  • 7. Introduction . . . • Writing your own functions is much like programming in other languages, except that you have the full resources of MATLAB’s functions at your disposal, making for very compact code. The MATLAB-6 and above environment has several windows at your disposal. • Command Window: The main window is the command window, where you will type all your commands, for small programs.
  • 8. Desktop Tools • Command Window – type commands • Workspace – view program variables – Clear/clear all is used to clear the workspace window – double click on a variable to see it in the Array Editor • Command History – view past commands – save a whole session using diary • Editor Window To write a program • Current Directory Window
  • 10. Matlab Screen • Command Window – type commands • 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
  • 11. Command History * A command history, which contains a list of all the commands that you have typed in the command window. * This makes it easy to cut and paste earlier lengthy commands, saving you the effort of typing it over again. * This window can also display the contents of the current directory.
  • 12. Workspace • The third window displays one of two things: * The launch pad from which you can browse the installed toolboxes and launch various tools as well as view demonstrations, and * The workspace, which lists all the variables that are currently in memory as well as their sizes.
  • 14. Vectors and Matices and their Manipulation
  • 15. Definition of Vectors & Matrices • MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore, vector and matrix operations are as simple as common calculator operations. • Vectors can be defined in two ways. * The first method is used for arbitrary elements: v = [1 3 5 7]; creates a 1x4 vector with elements 1, 3, 5 and 7. * Note that commas could have been used in place of spaces to separate the elements. that is v=[1,3,5,7]; • Additional elements can be added to the vector: v(5) = 8; yields the vector v = [1 3 5 7 8].
  • 16. • Previously defined vectors can be used to define a new vector. For example, with ‘v’ defined above a = [9 10]; b = [v a]; creates the vector b = [1 3 5 7 8 9 10].
  • 17. Second Method • The second method is used for creating vectors with equally spaced elements: t = 0: 0.1:10; creates a 1x101 vector with the elements 0, .1, .2, .3,...,10. Note that the middle number defines the increment. • If only two numbers are given, then the increment is set to a default of 1: For ex. k = 0:10; creates a 1x11 vector with the elements 0, 1, 2, ..., 10.
  • 18. * Matrices are defined by entering the elements row by row: M = [1 2 4; 3 6 8; 2 6 5]; creates the matrix * Transpose of M is denoted by M’, and displays as *The inverse of M is M-1 denoted in Matlab as M^-1and displays as * M(2,3) displays the element of second row and third column
  • 19. Arithmetic Operations • When applying addition, subtraction, multiplication and division between a scalar (that is a single number) and a vector we use +, -, *, and / respectively. Let Then a + b gives a - b gives
  • 20. aXb in Matlab a*b displays In Matlab a.*b gives element wise multiplication a+2 gives
  • 21. Algebraic manipulations • Scalar Calculations. The common arithmetic operators used in spreadsheets and program-ming languages such as BASIC are used in ‘Matlab'. • In addition a distinction is made between right and left division. The arithmetic operators are
  • 22. Operators (relational, logical) = = equal ~= not equal < less than <= less than or equal > greater than >= greater than or equal & AND | OR ~ NOT 1  pi 3.14159265… j imaginary unit, i same as j
  • 23. Special Matrices • null matrix: M = [ ]; • nxm matrix of zeros: M = zeros(n,m); nxm matrix of ones: M = ones(n,m); nxn identity matrix: M = eye(n);
  • 24. Help, Document and Demos • Matlab provides excellent tutorials that are accessible by typing >>demo • The Basic matrix operations tutorial under the Matrices tutorial, the Image Processing and Signal Processing tutorial under Toolboxes are highly recommended. • To get information on a particular function of Matlab, we type >>help function_name Example: >> help fft >> help mean
  • 25. Getting Help The Help pull-down menu gives you access to all the help pages included with MATLAB.
  • 26. • Comments in Matlab must be proceeded by % % This is a comment in Matlab. • To define a function in Matlab, we first create a function with the name of the function. *We then define the function in the file. *For example, the Matlab documentation recommends stat.m written as: function [mean,stdev] = stat(x) % This comment is printed out with help stat n = length(x); % assumes that x is a vector. mean = sum(x) / n; % sum adds up all elements. stdev = sqrt(sum((x - mean).^2)/n);
  • 27. Viewing Matlab Matrices as one Dimensional Arrays • Convert multi-dimensional to a one-dimensional array by simply using array_name(:) » a(:) ans = 1 4 7 2 5 8 3 6 9 Note that the elements in the one-dimensional array are arranged column by column, not row by row. This is the same convention that is used for two dimensional arrays in Fortran, and this will also be the convention that we will adopt for representing two dimensional arrays in C++.
  • 28. Displaying and Printing in Matlab • To plot an array or display an image, select the figure using: » figure(1); % select the figure to display. » clf % clear the figure from any % previous commands. • and use plot for displaying a one-dimen-sional array: » plot ([3 4 5 3 2 2]); % plots broken-line graph. • or use imagesc for displaying a two dimensional array (image):
  • 29. One-dimensional random access iterator (using an index array) [1 5 9 2 6 10 3 7 11 4 8 12] » I=[1 5 8 10]; % indices apply to one-dimensional array a(:) » a(I) ans = 1 6 7 4 – two dimensional iterators » a(1:2,1:3) ans = 1 2 3 5 6 7 .
  • 30. Working with Memory in Matlab • To keep track of how memory is allocated, we use whos » b=[34 54 56]; » a=[2 3 56]; » whos Name Size Bytes Class a 1x3 24 double array b 1x3 24 double array Grand total is 6 elements using 48 bytes We may then get rid of unwanted variables using clear » clear a; % removes the variable a from the memory. • We can use clear all to remove all variables from memory (and all functions and mex links) and close all to close all the figures and hence save a lot of memory.
  • 31. • Since Matlab supports dynamic memory allocation, it is possible to make inefficient use of the memory due to memory fragmentation problems. In this case, the pack command can be used to defragment the memory and help reclaim some of the memory. • To use memory efficiently, it is best to avoid changing the number of elements in an array during execution. It is best to • preallocate arrays before using them. To this end we can use zeros and ones: » a=zeros(3,4); % a two-dimensional 3x4 zero matrix. » b=ones(1,5); % an array of 5 elements of value 1.
  • 32. Evaluating one-dimensional functions in Matlab • To evaluate one-dimensional functions in Matlab we need to specify the points at which we would like our function to be evaluated at. • We can use either the built-in colon notation to specify the points » t=-1:0.5:1 t = -1.0000 -0.5000 0 0.5000 1.0000 or use linspace( ) » t=linspace(-2,4,5) % generates 5 points % between -2 and 4 t = -2.0000 -0.5000 1.0000 2.5000 4.0000 or use logspace( )
  • 33. Evaluating one-dimensional functions in Matlab (contd) • In general, all numbers in Matlab are double. Complex numbers are represented by multiplying the imaginary part by 1i. For example, 1+3j can be represented by 1+1i*3 or 1+3i. • All the well-known mathematical functions are defined in Matlab, and but they apply to to each element in the vector directly. • For example, cos([2 3 4]) is equivalent to [cos(2) cos(3) cos(4)].
  • 34. Evaluating two-dimensional functions in Matlab • To evaluate two-dimensional functions in Matlab we use the built-in function meshgrid ( ) with the ranges for x and y; eg: » [x,y]=meshgrid(0.1:0.1:0.3, 0.2:0.1:0.4) yields the matrices x and y given by: x = 0.1 0.2 0.3 0.1 0.2 0.3 0.1 0.2 0.3
  • 35. y = 0.2 0.2 0.2 0.3 0.3 0.3 0.4 0.4 0.4 • We may then apply any binary operation to x and y provided that we preceed each operation with a period. • For example x.*y represents the matrix where each element of x multiplies each element of y. • Similarly, exp(x.^2+y.^2) represents the matrix resulting from applying exp( ) to the sum of the squares of each of the elements of x and y.
  • 36. Flow Control • if • for • while • break • ….
  • 37. Control Structures • If Statement Syntax if (Condition_1) Matlab Commands elseif (Condition_2) Matlab Commands elseif (Condition_3) Matlab Commands else Matlab Commands end Some Dummy Examples if ((a>3) & (b==5)) Some Matlab Commands; end if (a<3) Some Matlab Commands; elseif (b~=5) Some Matlab Commands; end if (a<3) Some Matlab Commands; else Some Matlab Commands; end
  • 38. Control Structures • For loop syntax for i=Index_Array Matlab Commands end Some Dummy Examples for i=1:100 Some Matlab Commands; end for j=1:3:200 Some Matlab Commands; end for m=13:-0.2:-21 Some Matlab Commands; end for k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands; end
  • 39. Control Structures • While Loop Syntax while (condition) Matlab Commands end Dummy Example while ((a>3) & (b==5)) Some Matlab Commands; end
  • 40. Generation and plotting of basic signals
  • 42. To make a graph of y = sin(t) on the interval t = 0 to t = 10 we do the following: >> t = 0:0.3:10; >> y = sin(t); >> plot(t,y) ;
  • 43. Matlab Graphics x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2pi') ylabel('Sine of x') title('Plot of the Sine Function')
  • 44. Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on
  • 45. Multiple Plots t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) subplot(2,2,2) plot(t,y2)
  • 46. • Second, I can plot several different sets of data together: >> x = 0 : 0.1 : 10; >> y = sin(x); >> z = cos(x); >> plot(x, y, x, z);
  • 47. • Another useful command is axis, which lets you control the size of the axes. If I've already created the plot with both sine and cosine functions, I can resize it by typing >> axis([-5, 15, -3, 3]); which changes the plotting window so it looks like this:
  • 48. • f (x)=sin (x)3 +cos(3x) • over one period syms x; ezplot(sin(x)^3+ cos(3*x), [-pi pi], 1); grid on;
  • 49. Continuous and Discrete time plots k=0:20; y=binopdf(k,20,0.5); plot(k,y) k=0:20; y=binopdf(k,20,0.5); stem(k,y)
  • 54. Using Matlab Editors • Very small programs can be typed and executed in command window. • Large programs on other hand can be used the Matlab editor. • The complete program can be typed in the Matlab editor and saved as ‘file_name.m’, and can be retrieved when-ever necessary. • You can execute either directly from editor window or type the file name in the command window and press the enter button.
  • 55. Creating, Saving, and Executing a Script File % CIRCLE - A script file to draw a pretty circle function [x, y] = prettycirclefn(r) % CIRCLE - A script file to draw a pretty circle % Input: r = specified radius % Output: [x, y] = the x and y coordinates angle = linspace(0, 2*pi, 360); x = r * cos(angle); y = r * sin(angle); plot(x,y) axis('equal') ylabel('y') xlabel('x') title(['Radius r =',num2str(r)]) grid on
  • 56. Graph Functions (summary) • plot linear plot • stem discrete plot • grid add grid lines • xlabel add X-axis label • ylabel add Y-axis label • title add graph title • subplot divide figure window • figure create new figure window • pause wait for user response
  • 57. • clc: clear command window • clear all: clear all variables in workspace window • close all: closes all previous figure windows
  • 60. END