matlab fundamentals-an overview ugc asc burdwan univ sept2013
DESCRIPTION
MATLAB FundamentalsTRANSCRIPT
MATLAB® Fundamentals: MATLAB® Fundamentals: An OverviewAn Overview
byDr Amitava ChatterjeeDr. Amitava Chatterjee
Electrical Measurement and Instrumentation Laboratory,Electrical Engineering Department,
J d U i it K lk t I diJadavpur University, Kolkata, India.URL: http://www.jaduniv.edu.in/profile.php?uid=322
Short Term Course on Computational Tools and Open Source Software,
UGC-Academic Staff College, Burdwan University, Burdwan, India.02/09/2013
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB®1 – A Bird’s Eye ViewWh t i MATLAB??What is MATLAB??
MATLAB is an interactive software package which was developed to perform numerical calculations on vectors and matrices.
The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to provide easy access to matrix software developed by the LINPACK (linear system package)and EISPACK (Eigen system package) projects matrices.
This software package has been commercially available since 1984and is now widely accepted as a standard tool at most universities and industries worldwide.
In recent times, MATLAB has evolved as an excellent tool for
1MATLAB® is a registered trademark of MathWorks, Inc.
teaching and research. AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB – A Bird’s Eye ViewWh MATLAB??Why MATLAB??
MATLAB facilitates easy handling of many of the computations involved. In fact, the general feeling is that MATLAB should not be viewed as another complicated programming language, but more as a powerful calculator. MATLAB is an interactive system whose basic data element is an array that does not require dimensioning.y q g It has powerful built-in routines that enable a very wide variety of computations. Specific applications are collected in packages referred to as p pp p gtoolbox. It contains a wide variety of toolboxes which allow it to perform a wide range of applications from science and engineering. Thea wide range of applications from science and engineering. The toolboxes range from statistics to simulation, to control systems, to signal processing, to optimization, and so on.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB Fundamentals
The graphical interface to the MATLAB® workspace.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsSt ti MATLABStarting MATLAB
THE COMMAND WINDOWTHE COMMAND WINDOW
THE COMMAND HISTORY
THE WORKSPACE
THE CURRENT DIRECTORY
Some Useful Commands to Get Started Some Useful Commands to Get Started
>> demo
>> help <command>
>> doc <command>
>> lookfor <command>AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsSimple Arithmetic Operationsp p
Use it as a calculator:
>> 4.23*6.8 + 25/6
You can enter 345 as:
>> 3^45
You can enter a complex number 4 + 6i in MATLAB as:
>> 4 + 6i or >> 4 + 6*i
Write on MATLAB command:
>> x = 4 + 5*7
Change the previous command:
>> x = 4 + 5*7; What is the difference ??
Th i th dThen issue the command:
>> disp(x)AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsVector and Matrix Operationsp
Create a Row Vector (one dimensional array):
>> ur = [5 7 9 5 18 5];[ ]
Verify the size of the Row Vector:
>> size(ur)
Create a Column Vector (one dimensional array):
>> uc = [12; 8; 21; 6; 35; 67];
Verify the size of the Column Vector:
>> size(uc)
Perform Matrix Multiplication:
>> um1 = ur*uc or >> um2 = uc*ur
V if th i f th M t iVerify the size of the Matrix:
>> size(um1) or >> size(um2) AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsVector and Matrix Operations
Create a 5-by-3 Matrix:
>> m1 = [5 7 9; 5 18 5; 6 23 56; 54 6 70; 21 4 65]
Extract only the first row of Matrix m1:
>> row1 = m1(1,:)
Extract only the second column of Matrix m1:
>> col2 = m1(:,2)
Extract a submatrix of m1 comprising elements from 2nd andExtract a submatrix of m1 comprising elements from 2nd and 3rd rows and 1st and 2nd columns only:
>> subm1 = m1(2:3,1:2)
Transpose m1:
>> m1t = m1
Create a 5-by-5 Matrix comprising all zeros or all ones:
>> xz = zeros(5,5) or xo = ones(5,5) AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsVector and Matrix Operations
S El t C d f M t i d ASome Elementary Commands for Matrices and Arrays
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsVector and Matrix Operations
Matrices and Arrays: Operations and ManipulationAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
MATLAB FundamentalsVector and Matrix Operations
Matrices and Arrays: Matrix Analysis and Linear EquationsAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Variables and NumbersMATLAB Fundamentals
MATLAB does not require any type declarations or dimension statements. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of storage.
In MATLAB, X and x are not the same variable.
MATLAB by default displays only 4 decimals in the result of the
Issue the command: >> xx = 125.6578
calculations, but it actually performs numerical calculations in double precision, i.e. in 15 digits.
Issue the command: >> xx 125.6578
Study how the format command changes the display:
>> format longg
Then issue the next command: >> xx
: Again revert back the display format : >> format short
Then verify the display of the same variable: >> xx
Study the commands, whos and who. Is there any difference ??
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
The Colon OperatorMATLAB Fundamentalsp
The colon (:) is one of the most important MATLAB operators. It occurs inseveral different forms.
If you want to create a row vector of integers with unit spacing, issue the command: >> var1 = 1:10
If you want a similar array with nonunit spacing specify theIf you want a similar array with nonunit spacing, specify the increment (either positive or negative). Study the commands:
>> var2 = 3:6:33 or >> var3 = 33:-6:3
The spacing can be floating point numbers too:
>> var4 = 5:0.25:15 or >> var5 = 15:-0.25:5 or >> var6 = 0:pi/6:pi
You can delete a row or a column from a matrix using “:” and “[ ]”. You can delete the second column of a matrix as:
>> Xd = m1>> Xd = m1
>> Xd(:,2) = [ ]AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Some Useful CommandsMATLAB Fundamentals
f CTo clear the Command Window, type clc
To abort a MATLAB computation, type ctrl-cp , yp
To continue a line, type . . .
To delete a variable X, type clear X
To delete all variables from the work space, type clear all
To erase any statement from the command line, type ctrl-u
To turn WARNINGS issued by MATLAB on/off type warning on/offTo turn WARNINGS issued by MATLAB on/off, type warning on/off
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Save and Load CommandsMATLAB Fundamentals
Workspace variables do not persist upon exiting MATLAB. So one needs to store data for later use using save command. You can save the entire workspace as a binary MAT file:
>> save myworkspace.mat
Next time when you re-open MATLAB, you can load the entire k i l t dworkspace previously stored:
>> load myworkspace.mat
Save a variable as a MAT file:Save a variable as a MAT file:
>> save var1
Load this variable from the MAT file:Load this variable from the MAT file:
>> load var1
Similarly save a variable in a file in ASCII format and load a file, already stored in ASCII format, in MATLAB workspace:
>> save var1.dat var1 -ascii and >> load var1.datAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (two-dimensional)MATLAB Fundamentals
Plot the graph of e-0.2xsin(x) over the domain 0 to 6.>> x = 0:pi/20:6*pi;>> plot(x,exp(-0.2*x).*sin(x),'r'),gridp ( , p( ) ( ), ),g>> axis([0 20 -0.4 0.8])>> xlabel('time') >> ylabel('amplitude')>> title('Plot of the Exponentially Damped Sine Function') title( Plot of the Exponentially Damped Sine Function )
0.6
0.8Plot of the Exponentially Damped Sine Function
0 2
0.4
itude
0
0.2
ampl
0 2 4 6 8 10 12 14 16 18 20-0.4
-0.2
time
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (two-dimensional)MATLAB Fundamentals
Plotting multiple data sets (or functions) in one plot. >> x = 0:pi/20:6*pi;>> x = 0:pi/20:6*pi;
>> y1 = 5*cos(x);
>> y2 = 0.5*sin(x); y ( );
>> y3 = 2.5*cos(x);
>> plot(x,y1,'r--',x,y2,'b-',x,y3,'k:')
>> axis([0 18 -5 5])
>> xlabel('0 \leq x \leq 6\pi')
>> ylabel('Cosine functions')>> ylabel( Cosine functions )
>> legend('5*cos(x)','0.5*sin(x)','2.5*cos(x)')
>> title('Typical example of multiple plots')
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (two-dimensional)MATLAB Fundamentals
Plotting multiple data sets (or functions) in one plot. >> x = 0:pi/20:6*pi; >> y1 = 5*cos(x); >> y2 = 0.5*sin(x); >> y3 = 2.5*cos(x); …..
4
5Typical example of multiple plots
5*cos(x)0 5*sin(x)
>> title('Typical example of multiple plots')
2
3
s
0.5 sin(x)2.5*cos(x)
-1
0
1
osin
e fu
nctio
ns
-3
-2
Co
0 2 4 6 8 10 12 14 16 18-5
-4
0 x 6
AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (two-dimensional)MATLAB Fundamentals
Plotting multiple data sets (or functions) using subplot. >> x = 0:pi/20:6*pi; >> y1 = 5*cos(x);>> y1 = 5*cos(x); >> y2 = 0.5*sin(x); >> y3 = 2.5*sqrt(x); >> y4 = 12*exp(-0.5*x);>> subplot(2,2,1), plot(x,y1,'r--') >> subplot(2 2 2) plot(x y2 'b-')>> subplot(2,2,2), plot(x,y2, b )>> subplot(2,2,3), plot(x,y3,'k:') >> subplot(2,2,4), plot(x,y4,'m-.')>> subplot(2,2,1), axis([0 18 -5 5]) >> subplot(2,2,1), xlabel('0 \leq x \leq 6\pi') >> subplot(2,2,1), ylabel('Cosine function') p ( , , ), y ( )>> subplot(2,2,1), legend('5*cos(x)')>> subplot(2,2,1), title('Typical example of a subplot-1') …
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (two-dimensional)MATLAB Fundamentals
Plotting multiple data sets (or functions) using subplot. >> x = 0:pi/20:6*pi; >> y1 = 5*cos(x); >> y2 = 0.5*sin(x); >> y3 = 2.5*sqrt(x); >> y4 = 12*exp(-0.5*x); >> subplot(2,2,1), plot(x,y1,'r--') >> subplot(2,2,2), plot(x,y2,'b-') …
5
n
Typical example of a subplot-1 0.5
Typical example of a subplot-2
5*cos(x) 0.5*sin(x)
0
Cos
ine
func
tion
0
Sin
e fu
nctio
n0 5 10 15
-5
0 x 6
C
0 5 10 15
-0.5
0 x 6
Typical example of a subplot-3 Typical example of a subplot-4
5
10
e ro
ot fu
nctio
n
5
10
entia
l fun
ctio
n2.5*sqrt(x) 12*exp(-0.5*x)
0 5 10 150
Squ
are
0 x 6
0 5 10 15
0
0 x 6
Exp
one
AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (three-dimensional)MATLAB Fundamentals
Plot the Mexican Hat.>> [x y] = meshgrid(-8:0.5:8);>> r = sqrt(x.^2 + y.^2)+eps;q ( y ) p ;>> z = sin(r)./r;>> mesh(z)
1
0
0.5
40-0.5
0
010
2030
40
010
20
30AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Plot Commands (three-dimensional)MATLAB Fundamentals
Plot the Mexican Hat.>> [x y] = meshgrid(-8:0.5:8);>> r = sqrt(x.^2 + y.^2)+eps;q ( y ) p ;>> z = sin(r)./r;>> surf(z), shading flat or >> figure, surf(z), shading flat
1
0
0.5
40-0.5
0
010
2030
40
010
20
30AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Scripts and FunctionsProgramming in MATLAB
p A script file is an external file that contains a sequence of MATLABstatements. Script files are called M-files and they have .m in their filename extensionfilename extension.
Scripts do not accept input arguments or return output arguments. They operate on data in MATLAB workspaceThey operate on data in MATLAB workspace.
M-files can also be written in form of functions that can accept input arguments and return output arguments Internal variables remainarguments and return output arguments. Internal variables remain local to the function. If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functionsthe functions.
It is easy to edit a script file if we wish to remove any error(s) and then the sequence of statements can be executed whenever desiredthen the sequence of statements can be executed whenever desired by typing the <file name> in MATLAB command line in the command window.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
How to Write and Execute Script M-files ??Programming in MATLAB
p fLet us consider that we wish to write the Mexican Hat
program as an M-file.
Use the MATLAB editor to create a new file:
File New Script (or M-file)
E t th i f MATLAB t t tEnter the series of MATLAB statements:[x y] = meshgrid(-8:0.5:8);r = sqrt(x.^2 + y.^2)+eps;z = sin(r)./r;mesh(z)
Save the file, for example, as mexhat.m.Save the file, for example, as mexhat.m.
Run the file, in the command line, by typing:
>> mexhat
When the execution completes, the variables remain in the workspace. Verify this by typing: >> whos
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
M-file FunctionsProgramming in MATLAB
fLet us consider that we wish to write an M-file function that
will calculate squares and cubes of the sum of two numbers.
Use the MATLAB editor to create a new function:
File New Function
E t th i f MATLAB t t tEnter the series of MATLAB statements:function [outp1 outp2] = sqre_cube(inp1,inp2)outp1 = inp1^2 + inp2^2+ 2*inp1*inp2;outp2 = inp1^3 + inp2^3 + 3*inp1*inp2*(inp1 + inp2);outp2 inp1 3 inp2 3 3 inp1 inp2 (inp1 inp2);end
Save the file as sqre_cube.m.
Run the file, in the command line, by typing:
>> [x y] = sqre_cube(5,4)
R th fil i i th d li b t iRun the file again, in the command line, by typing:
>> [x y] = sqre_cube(6,7)AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Control Flow and OperatorsProgramming in MATLAB
pMATLAB has several flow control constructs:
The “if … end” structure
The “if … else … end” structure
The “if … elseif … else … end” structure
The “for … end” loop
The “while … end” loop
Th “b k” t t t ( b d t t i t hil l The “break” statement (can be used to terminate a while loop or to exit a for loop).
The “continue” statement (can be used to exit a for loop to pass immediately to the next iteration of the loop, skipping the remaining statements in the loop).
The “return” statement, the “switch” statement etc.The return statement, the switch statement etc.
One can study the syntax by typing the help command (e.g. help for)
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Control Flow and OperatorsProgramming in MATLAB
pIF Conditionally execute statements.
The general form of the if statement is:The general form of the if statement is:IF expression
statementsELSEIF expression
statementsELSEELSE
statementsEND
FOR Repeat statements a specific number of times.
The general form of a for statement is:The general form of a for statement is:
FOR variable = expression, statement, ..., statement ENDAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Control Flow and OperatorsProgramming in MATLAB
Arithmetic Operators and Special CharactersAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Control Flow and OperatorsProgramming in MATLAB
p
Array Operators
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Control Flow and OperatorsProgramming in MATLAB
p
Relational and Logical OperatorsAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Control Flow and OperatorsProgramming in MATLAB
p
Operator PrecedenceAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
fprintf Statement for Displaying Output on the ScreenProgramming in MATLAB
fp f f p y g pIn MATLAB, the command fprintf can be utilized both for displaying the output on the screen as well as for writing the
t t t filoutput to a file.
A script M file that executes a sequence of statements andA script M-file that executes a sequence of statements and displays the result on the screen:
x array = [5 5 8 7 12 4 34 7 67 9 -3 2 6 8];x_array = [5.5 8.7 12.4 34.7 67.9 -3.2 6.8];fprintf('\nmaximum value = %8.4f', max(x_array));fprintf('\nminimum value = %8.4f', min(x_array));fprintf('\naverage value = %8.4f', mean(x_array));fprintf('\n');
O il h th f t f di l if h / h i h One can easily change the format of display if he/she wishes to.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
fprintf Statement for Saving Output to a FileProgramming in MATLAB
fp f f g pOne can save the results of some computation to a file in text format, using the following steps:
Open a file using fopen
Write the output using fprintf
Cl th fil i f lClose the file using fclose
Change the previous script M-file as shown below and g p pexecute it in the command prompt:
x_array = [5.5 8.7 12.4 34.7 67.9 -3.2 6.8];outp = fopen('array.txt','wt');fprintf(outp,'\nmaximum value = %8.4f', max(x_array));fprintf(outp,'\nminimum value = %8.4f', min(x_array));fprintf(outp,'\naverage value = %8.4f', mean(x array));fprintf(outp, \naverage value %8.4f , mean(x_array));fprintf(outp,'\n');fclose(outp);
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Programming in MATLAB
Some Useful Workspace and File CommandsAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Programming in MATLAB
Some Predefined Variables and Math Constants
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Introduction to SimulinkMATLAB/Simulink
kSimulink is a user-friendly environment created in MATLABplatform, essentially for the purpose of graphical, model-based simulation of dynamic systems.based simulation of dynamic systems.
The key features of Simulink are: Graphical editor for building and managing hierarchical blockdiagramsdiagrams Libraries of predefined blocks for modeling continuous-timeand discrete-time systems Simulation engine with fixed-step and variable-step ODEg p psolvers Scopes and data displays for viewing simulation results Project and data management tools for managing model files
d d tand data Model analysis tools for refining model architecture andincreasing simulation speed MATLAB Function block for importing MATLAB algorithms intoMATLAB Function block for importing MATLAB algorithms intomodels ….
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
How to Start SimulinkMATLAB/Simulink
kType simulink in command prompt. or
click here to start
choose current to start
simulinkcurrent
directory
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Simulink Library BrowserMATLAB/Simulink
k y
Library Browserygives access tovarious standard oradditional blocksthat can be utilizedthat can be utilizedto build complicatedmodels. AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
g kFrom the Simulink Library Browser Menu, select: File New Model. An empty model opens in the Simulink Editor.Simulink Editor.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
Edit the blank model by dragging and dropping blocks from the library browser, adding appropriate sources and sinks, and making suitable connections to build your own model.
drag and drop from the Sources in the Library
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
double click the sine block to change its parameter values
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
add another block in your model AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
source 1
source 2
sink (oscilloscope)
source 2
MUXconnector
The Complete ModelAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
set the configuration parameters before running the simulation
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating a New Simulink ModelMATLAB/Simulink
click here to start simulation total simulation time
autoscale
scope double click on thebl k t scope
parametersscope block todisplay outputwaveform
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Saving the Simulink ModelMATLAB/Simulink
the simulink modelcreated is saved, forfuture use, as sim1.mdlin your chosendirectory
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Reusing an Existing Simulink ModelMATLAB/Simulink
double clicksim1.mdl toopen thispsimulink model
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating GUIsGraphical User Interfaces (GUIs)
g GIn MATLAB, one can use GUIDE, the MATLAB Graphical User Interface Development Environment to create GUIs.
A GUI is essentially a graphical display which allows a user to pictorially interact with a program. It comprises the following basic elements:
Components – Push buttons, sliders, radio buttons, check boxes etc., which enable the user to interact with a program.program.
Figure – A graphical window which houses all these components.
Callbacks – Code modules that are used to enable user interaction with the program.
To write a GUI, type in the command prompt:>> guide
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Creating GUIsGraphical User Interfaces (GUIs)
g G
Select this and click OK to create a blank, new GUI.AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
The Layout EditorGraphical User Interfaces (GUIs)
The blank GUI is displayed in the Layout Editor, which acts as thecontrol panel for all of the GUI Tools.
Layout Area
ComponentPalette
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
The Layout EditorGraphical User Interfaces (GUIs)
Lay out your GUI, by dragging components like Slider, Edit Text, CheckBox, Push Button etc. from the Component Palette into the Layout Area.
Layout Area
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
The Layout EditorGraphical User Interfaces (GUIs)
Lay out your GUI, by dragging components like Slider, Edit Text, CheckBox, Push Button etc. from the Component Palette into the Layout Area.
Layout Area
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
The Layout EditorGraphical User Interfaces (GUIs)
Lay out your GUI, by dragging components like Slider, Edit Text, CheckBox, Push Button etc. from the Component Palette into the Layout Area.
Layout Area
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Design a GUI in MATLAB to determine square root of a number, usingNewton’s method. In the GUI, enter the number to be square-rooted, press theStart button, and the GUI should show the result in an iterative manner.
Right click anywhere inRight click anywhere inthe Layout Area to reachthe figure’s PropertyInspector. AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Click the figure’sClick the figure sPropertyInspector and setthe figure’s Nameproperty toproperty toNewton.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Make the GUIResizable. ClickTools GUIOptions. AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
UnderProportionalwhen the windowwhen the windowis resized, theGUI componentsalso get resized. AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Place aStatic Textcontrol.Right clickto reach itsPropertyInspector.p AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Change itsString propertyto Enter thenumber tosquare rootand PressStart. The Tagof thiscomponent istext1.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Add anEdit Textcontrol. Setits Stringproperty toblank. TheTag of thiscomponentis edit1.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Next, activate the figure using Editor in View option and saving it asNewton.fig.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
This automatically opens the application M-file Newton.m.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Add anotherStatic TextStatic Textcontrol. Set itsString propertyto Output anditsitsHorizontalAlignment to left.The Tag of thiscomponent iscomponent istext2.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Add a PushButton. Set itsString propertyto Start. TheTag of thiscomponent ispushbutton1. AMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Now, activate the figure again using Editor in View option, to updateNewton.m. Then the pushbutton1_Callback sub function is programmed as:
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Save your work and activate the figure again to test it. Then Run the figure.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
Save your work and activate the figure again to test it. Then Run the figure.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
An ExampleGraphical User Interfaces (GUIs)
The GUI Newton.fig shows the following result.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
Read an image using imread command in command line:
>> img1 = imread('pout.tif');
Check the row and column dimensions of the image:Check the row and column dimensions of the image:
>> [img_rows, img_cols] = size(img1)
Display the image using imshow command in command line:
>> imshow(img1)
pout.tifAMITAVA C
HATTERJEE
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
Images are written to disc using the function imwrite:
>> imwrite(img1, 'pout_test.tif');
Obtain an image file details using the command imfinfo:Obtain an image file details using the command imfinfo:
>> imfinfo pout_test.tif
Create a histogram to view the intensity distribution:
>> figure, imhist(img1)
Histogramof pout.tif
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
Improve the contrast of this image using the function histeq which performs histogram equalization:
>> img2 = histeq(img1);g ( g )
Display the histogram equalized image in a new figure window:
>> figure, imshow(img2)
Histogram equalizedpout.tif
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
View the intensity distribution of the histogram equalized version of pout.tif:
>> figure, imhist(img2)
Histogram ofhistogramequalizedequalizedversion ofpout.tif
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
Read a new grayscale image moon.tif and display this image:
>> img_moon = imread('moon.tif');
>> imshow(img moon)>> imshow(img_moon)
Use the command imadjust to perform intensity adjustment for moon.tif:
>> img_moon1 = imadjust(img_moon, [0.5 0.75], [0 1], 2);
fi i h (i 1)>> figure, imshow(img_moon1)
Intensityadjustedadjustedversion ofmoon.tif
moon.tif
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
To perform image segmentation of moon.tif, use function graythresh that automatically computes an appropriate threshold:
>> thr_intensity = graythresh(img_moon);
Use the command im2bw to convert grayscale moon.tif into a binary image using thresholding and display the thresholded image:
>> img_moon_bw = im2bw(img_moon,thr_intensity);
>> figure, imshow(img_moon_bw)
Automaticthresholdingthresholdingbasedsegmentedmoon.tif
moon.tif
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
An example of linear spatial filtering:>> img_pepper = imread('peppers.png');>> figure, imshow(img_pepper)
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
An example of linear spatial filtering:>> img_pepper = imread('peppers.png');>> figure, imshow(img_pepper)
i b2 (i )>> img_pepper_gr = rgb2gray(img_pepper);>> figure, imshow(img_pepper_gr)
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
An example of linear spatial filtering:>> img_pepper = imread('peppers.png');>> figure, imshow(img_pepper)
i b2 (i )>> img_pepper_gr = rgb2gray(img_pepper);>> figure, imshow(img_pepper_gr)>> img_pepper_grn = imnoise(img_pepper_gr,'gaussian',0,0.01);>> figure, imshow(img pepper grn) figure, imshow(img_pepper_grn)
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
An example of linear spatial filtering:…>> img_pepper_grn = imnoise(img_pepper_gr,'gaussian',0,0.01);
fi i h (i )>> figure, imshow(img_pepper_grn)>> H_mask1 = fspecial('average');>> H_mask2 = fspecial('gaussian');>> img pepper grf1 = imfilter(img pepper grn,H mask1,'replicate'); img_pepper_grf1 imfilter(img_pepper_grn,H_mask1, replicate );>> img_pepper_grf2 = imfilter(img_pepper_grn,H_mask2,'replicate');>> figure, imshow(img_pepper_grf1)
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
Useful Images Processing CommandsMATLAB in Image Processing
An example of linear spatial filtering:…>> img_pepper_grn = imnoise(img_pepper_gr,'gaussian',0,0.01);
fi i h (i )>> figure, imshow(img_pepper_grn)>> H_mask1 = fspecial('average');>> H_mask2 = fspecial('gaussian');>> img pepper grf1 = imfilter(img pepper grn,H mask1,'replicate'); img_pepper_grf1 imfilter(img_pepper_grn,H_mask1, replicate );>> img_pepper_grf2 = imfilter(img_pepper_grn,H_mask2,'replicate');>> figure, imshow(img_pepper_grf1)>> figure, imshow(img_pepper_grf2)
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
ReferencesL i MATLAB 7 R l 14 MATLAB® & Si li k®Learning MATLAB 7, Release14, MATLAB® & Simulink®
Student Version, The MathWorks, Inc., 2005.
Ed Overman A MATLAB Tutorial Department of Ed Overman, A MATLAB Tutorial, Department of Mathematics, The Ohio State University, 2012.
David Houcque, Introduction to MATLAB for Engineering David Houcque, Introduction to MATLAB for Engineering Students, Northwestern University, 2005.
Simulink® Getting Started Guide, R2013a, MATLAB® & g , ,Simulink®, The MathWorks, Inc., 2013.
MATLAB/Simulink Tutorial, ECEN 2060, Colorado University, 2008.
R. C. Gonzalez, R. E. Woods, and S. L. Eddins, Digital Image P i i MATLAB P Ed ti 2005Processing using MATLAB, Pearson Education, 2005.
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA
AMITAVA CHATTERJE
E
ELECTRIC
AL ENGIN
EERING D
EPARTMENT
JADAVPUR U
NIVERSITY, K
OLKATA, IN
DIA