Professional Documents
Culture Documents
PsiPhiETC
www.psiphi.in
January 1, 2012
PsiPhiETC (www.psiphi.in)
January 1, 2012
1 / 74
Motivation
PsiPhiETC (www.psiphi.in)
January 1, 2012
2 / 74
Motivation
What is MATLAB?
MATrix LABoratory High-performance scientic computation MATLAB System Integrates
1 2 3
Desktop Tools and Dev Environment Mathematical Functions Library Programming Graphics External Interface
PsiPhiETC (www.psiphi.in)
January 1, 2012
3 / 74
Motivation
Features of MATLAB!
Library of Mathematical Functions Interactive Computations through Command Window Programming for Complex Problems Graphics for Data Analysis and Visualization Graphical User Interface (GUIDE) Specialized Toolboxes (Simulink)
PsiPhiETC (www.psiphi.in)
January 1, 2012
4 / 74
Motivation
Course Contents
# 1 2 3 4 5 6 7 8
Topic Introduction Getting Started Interactive Computation Programming and Scripts Programming and Functions Graphics-1 Graphics-2 GUIDE & Simulink
PsiPhiETC (www.psiphi.in)
January 1, 2012
5 / 74
Motivation
Installation
Available for all major computing platforms (Windows, Unix, Mac) World Wide Web: http://www.mathworks.com Student and Professional Versions Read the installation instructions carefully Check Installation
PsiPhiETC (www.psiphi.in)
January 1, 2012
6 / 74
Motivation
Menu [Desktop Tools (Layout), Help Browser], Editor, Current Directory [pwd, ls, window, M-Lint], Command Window [x=1, Workspace, x+1, ans], Command History [Selection, Execution], Docking, Start, Ref:GSG-Ch7
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 7 / 74
Motivation
1 2 3 4
Commands:
lookfor string help topic which topic
PsiPhiETC (www.psiphi.in)
January 1, 2012
8 / 74
Motivation
Motivation
Variable Names row vec ( [], col sep), col vec (row sep) , . . . , ; a::b linspace(a,b,n) +, -, cross, dot, .* , ./, .^ sin, cos, log, sqrt format
1 2 3 4 5 6 7 8 9
rv=[1,2,3] cv=[1;2;3] v1=1:1:3 v2=linspace(1,3,3) v3=v1' v4=v1+v2 v5=v1.*v2 v6=sqrt(v1) format long e
PsiPhiETC (www.psiphi.in)
January 1, 2012
10 / 74
Motivation
Simple Plots
x=linspace(0,2*pi,100); y=sin(x); plot(x,y); xlabel('x'); ylabel('sin(x)'); title('x vs sin(x)'); axis tight;grid on;
1 2 3
plot (x,y) axis tight | equal xlabel (string) ylabel (string) title (string) grid on | off
4 5 6 7
PsiPhiETC (www.psiphi.in)
January 1, 2012
11 / 74
Motivation
MATLAB Editor
Menu Bar Tool Bar Editing Space Line Number Code Analysis Message Document Bar Status Bar Execution and Debugging
PsiPhiETC (www.psiphi.in)
January 1, 2012
12 / 74
Motivation
MATLAB Script
1 2
% Script to find triangle area % The help for ScriptExample.m base=2; %triangle base height=1; %triangle height Area=(1/2)*base*height;
% for comments H1 Line, Help Valid MATLAB commands and expressions Comment %, Keywords Saving Execution
3 4 5 6
1 2 3 4 5 6 7
lookfor triangle help ScriptExample ScriptExample base height Area clear all
PsiPhiETC (www.psiphi.in)
January 1, 2012
13 / 74
Motivation
MATLAB Functions
function [argout]=FN(argin) H1 Line % for comments Saving exist (FN) argin pass by value variable are local
2 3 4 5 6
function [A]=FunctionExample(b,h) % FunctionExample for triangle area % The help for FunctionExample.m % Syntax A=FunctionExample(b,h) A=(1/2)*b*h;
1 2 3 4 5 6
PsiPhiETC (www.psiphi.in)
January 1, 2012
14 / 74
Interactive Computations
Matrix Creation?
Enclosed within square bracket [] Entered row wise Column Separator: space or , Row Separator: ; . . . (ellipsis) is used for continuation
1
Interactive Computations
Matrix Indexing
A(i,j)=aij size(A)=[m,n]
1 2
. . . am1 n2 . . . . . . . . . am2 n2
3 4 5 6 7
>> A=[1,2,3;... 4,5,6] >> size(A) >> A(2,3) >> A(1:2,2:3) >> A(2,2:end) >> A(:,2:end)
PsiPhiETC (www.psiphi.in)
January 1, 2012
16 / 74
Interactive Computations
Matrix Manipulation
Element: A(i,j)=aij Row: A(m,:)=v1n Column: A(:,n)=vm1 Submatrix: A(m1 : m2 , n1 : n2 ) = B(m2 m1 )(n2 n1 ) Appending: A=[A, vm1 ], A=[A; v1n ] Deleting: A(m,:)=[], A(:,n)=[] eye(m,n), zeros(m,n), ones(m,n), magic(n)
1 2 3 4 5 6 7 8 9 10 11 12 13
>>A=[1,2,3;4,5,6]; >>A(1,2)=9; >>A(2,:)=[9,9,9] >>A(:,3)=[9;9] >>A(1:2,2:3)=[9,9;9,9] >>A(3,:)=[9,9,9]; >>A(:,4)=[9;9;9]; >>A(3,:)=[] >>A(:,4)=[] >>eye(3) >>zeros(3) >>ones(3) >>magic(3)
PsiPhiETC (www.psiphi.in)
January 1, 2012
17 / 74
Interactive Computations
Matrix Operations
1 2
Arithmetic: +, -, *, /, ^ Relational: <, >, <=, >=, ==, = Logical Operations: &, |, NOT Logical Functions: all, any, exists, isempty, isinf, isnan
3 4 5 6 7 8 9 10 11
>> >> >> >> >> >> >> >> >> >> >>
A=eye(2,2) B=ones(2,2) C=A*B R1=A<B R2=A==B R3=A=B L1=A&B L2=A|B F1=all(A) F2=any(A) F3=isempty(A)
PsiPhiETC (www.psiphi.in)
January 1, 2012
18 / 74
Interactive Computations
Trigonometric: sin , asin, . . . Exponential: exp , log, . . . Algebraic: sqrt, nthroot, . . . Complex: abs, angle, conj, img, real Round-off: oor, ceil, x, mod, rem Matrix: expm, sqrtm
1 2 3 4 5 6 7 8 9 10
>> >> >> >> >> >> >> >> >> >>
sin(pi/6) exp(1) sqrt(2) z=1+i abs(z) angle(z) floor(1.9) ceil(1.1) A=ones(2,2) expm(A)
PsiPhiETC (www.psiphi.in)
January 1, 2012
19 / 74
Interactive Computations
Character Strings
Single Quote: string Manipulating string eval num2str, str2num lower, upper strcmp, strncmp strcat, ndstr
1 2 3 4 5 6 7 8 9 10
>> >> >> >> >> >> >> >> >> >>
s='Hello World' s(2)='E' eval('x=2*3') y='2.3' zn=str2num(y) zs=num2str(x) s1=lower(s) s2=strcat(s,s1) strcmpi('Hello','hello') findstr(s,'W')
PsiPhiETC (www.psiphi.in)
January 1, 2012
20 / 74
Interactive Computations
1 2 3 4 5 6 7 8 9 10
>> >> >> >> >> >> >> >> >> >>
x=linspace(0,2*pi,10) y=sin(x) save clear all load save('myfile','x') clear all load myfile load datafile.txt d=load('datafile.txt')
PsiPhiETC (www.psiphi.in)
January 1, 2012
21 / 74
Programming in MATLAB
Script Files
.m le containing valid commands Name shall starts with a letter and can have letters, digits and _ Avoid clash with names of built-in function (exist(fn)) Variable Name = File Name Works on global workspace variables Use of clear all
1 2 3 4 5
6 7
% solvex.m (Ref: RP) % 5 x1+2r x2+r x3=2 % 3 x1+6 x2+(2r-1) x3=3 % 2 x1+(r-1) x2+3r x3=5 A=[5, 2*r,r;3, 6, 2*r-1; ... 2, r-1, 3*r]; b=[2;3;5]; x=A\b
1 2
r=1; solvex
PsiPhiETC (www.psiphi.in)
January 1, 2012
22 / 74
Programming in MATLAB
Function Files
function [argout] = FunctionName (argin) Local Variables Pass-by value Readability: H1, help Modularity: subfunction Robustness: nargin, error(message) Expandability: varargin
1 2 3 4 5 6 7 8
function [det_A, x]=solvexf(r) % SOLVEXF solves eqn with par r % Function file solvexf.m % To call this function, type: % [det_A,x]=solvexf(r) % r is i/p and det_A & x are o/p A=[5, 2*r, r; 3,6, 2*r-1; 2, ... r-1, 3*r]; b=[2;3;5]; det_A=det(A); x=A\b;
9 10 11
PsiPhiETC (www.psiphi.in)
January 1, 2012
23 / 74
Programming in MATLAB
1 2 3 4 5 6 7
Programming in MATLAB
1 2 3
1 2 3 4
PsiPhiETC (www.psiphi.in)
January 1, 2012
25 / 74
Programming in MATLAB
1 2 3
PsiPhiETC (www.psiphi.in)
January 1, 2012
26 / 74
Programming in MATLAB
1 2 3 4 5
switch flag case val1 block 1 computation case val2 block 2 computation otherwise last block computation end
1 2 3 4 5 6 7
color= input('color= ','s'); switch color case 'red' c=[1, 0, 0]; case 'green' c=[0, 1, 0]; case 'blue' c=[0, 0, 1]; otherwise error('invalid') end
PsiPhiETC (www.psiphi.in)
January 1, 2012
27 / 74
Programming in MATLAB
break terminates for or while loop continue pass control to the next iteration of for or while loop return return to invoking function
PsiPhiETC (www.psiphi.in)
January 1, 2012
28 / 74
Programming in MATLAB
1 2
Age=input(Age plz?) Name=input(Name plz?, s) script/function keyboard k statements return pause, pause(n)
3 4 5 6 7 8 9 10 11
Age=input('Age Plz?'); Name=input('Name Plz?','s'); keyboard; >> Age >> Name k>> Age=21 k>> Name='ABC' k>> return pause(10) disp(Age) disp(Name)
PsiPhiETC (www.psiphi.in)
January 1, 2012
29 / 74
Programming in MATLAB
Input/Output
d = fopen (fn, r|w|a) fclose (d) fprintf (d, format, x) x=fscanf (d, format) sscanf, sprintf fgets, fgetl
1 2 3 4 5 6 7 8 9 10
fid=fopen('a.txt','w'); fprintf(fid,'pi=%10.8f \n',pi); s=sprintf('e=%10.8f\n',exp(1)); fprintf(fid,s); fclose(fid); fid=fopen('a.txt','r'); s1=fgets(fid); s2=fgetl(fid); PI=sscanf(s1,'pi=%f'); E=sscanf(s2,'e=%f');
PsiPhiETC (www.psiphi.in)
January 1, 2012
30 / 74
Figure
h=gure h=gcf gure(h) Edit > Figure Properties Property Editor > Figure
Name: string Color: [r,g,b], (r , g, b) [0, 1] NumberTitle: {on}|off
More Properties
Menubar: {gure}|none Position: [x,y,w,h]
PsiPhiETC (www.psiphi.in)
January 1, 2012
31 / 74
1 2
h=gure or h=gcf get (h) -> PropertyName, PropertyValue get (h) -> PropertyName {PropertyValueActive} | PropertyValueOptional set (h, PropertyName, PropertyValue)
3 4 5
PsiPhiETC (www.psiphi.in)
January 1, 2012
32 / 74
Axes
axes a=axes > Handle a a=axes (PropertyName, PropertyValue) Important Properties:
Color FontSize, FontWeight, . . . LineWidth, . . . XGrid, YGrid XLim, YLim XTick, YTick XTickLabel, YTickLabel
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 33 / 74 1 2
a=axes; get(a);
5 6 7 8
(a, 'Color' , [1,1,0]) (a, 'LineWidth' , 3) (a, 'XGrid' , 'on') (a, 'YLim' , [-1, 1]) (a, 'XTick' , [0.2,0.6,0.9]) (a,'XTickLabel',{0.2,'six',0.9} ) (a, 'YTick' , [0.3,0.6,0.9]) (a,'YTickLabel',{'y1',0.6,'y_2'} )
PsiPhiETC (www.psiphi.in)
January 1, 2012
34 / 74
Plot
1 2 3
PsiPhiETC (www.psiphi.in)
January 1, 2012
35 / 74
1 2 3 4
p=plot (x,y) get (p) set (p) set (p, PropertyName, PropertyValue)
5 6 7
x=0:10;y=x.^2; p=plot(x,y); set(p , 'Color' , [0,1,0]); set(p , 'LineWidth' , 3); set(p , 'LineStyle' , '-'); set(p , 'Marker' , 'o'); set(p , 'MarkerSize' , 12);
PsiPhiETC (www.psiphi.in)
January 1, 2012
36 / 74
Overlay Plot
1 2
plot (x1,y1,x2,y2) plot ( x1,y1,LS1, x2,y2,LS2) plot (x1,y1,LS, PropName, PropValue) hold on plot (x2,y2, LS, PropName, PropValue) hold off; line (x, y, PropName, PropValue)
3 4 5 6 7 8 9
x1=-5:5; y1=x1.^2; x2=-5:5; y2=x2.^3; p1=plot(x1,y1,'r-*'); set(p1,'Linewidth',3); hold on; p2=plot(x2,y2,'b:o'); set(p2,'Linewidth',4); hold off; grid on; set(gca,'Linewidth',2);
PsiPhiETC (www.psiphi.in)
January 1, 2012
37 / 74
Text on Plot
text(x,y,string) text(x,y,string,PropertyName, PropertyValue) t=text(x,y,string) get(t) , set (t) set (t,PropertyName, PropertyValue) gtext (string) gtext (string,PropertyName, PropertyValue) To Get Coordinate of a point: [x,y]=ginput (1)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 38 / 74 1 2 3 4 5 6
Axis
1 2 3
PsiPhiETC (www.psiphi.in)
January 1, 2012
39 / 74
Legend
1 2 3 4 5
x1=-5:5; y1=x1.^2; x2=-5:5; y2=x1.^3; p=plot(x1,y1,'r',x2,y2,'g'); set(p,'Linewidth',4); l=legend('data x1-y1', ... 'data x2-y2'); set(l,'Location','NorthWest');
PsiPhiETC (www.psiphi.in)
January 1, 2012
40 / 74
Subplot
1 2 3 4 5
x1=-5:5; y1=x1.^2; x2=-5:5; y2=x2.^3; subplot (1,2,1); plot (x1,y1,'g','Linewidth',3); subplot (1,2,2); plot(x2,y2,'r','Linewidth',3);
PsiPhiETC (www.psiphi.in)
January 1, 2012
41 / 74
Findobj
1 2 3 4
5 6 7
x1=-5:5; y1=x1.^2; x2=-5:5; y2=x2.^3; plot (x1,y1,'r',x2,y2,'g'); h1=findobj('Color','r'); set(h1,'Linewidth',3); h2=findobj('Color','g'); set(h2,'Color','b','Linewidth',3);
PsiPhiETC (www.psiphi.in)
January 1, 2012
42 / 74
PsiPhiETC (www.psiphi.in)
January 1, 2012
43 / 74
Plotting Process
Creating Graph Exploring Data Editing Graph Components Annotation Graphs Printing and Exporting Graphs Adding and Removing Contents Saving Graph for Reuse
PsiPhiETC (www.psiphi.in)
January 1, 2012
44 / 74
Figure Tools
PsiPhiETC (www.psiphi.in)
January 1, 2012
45 / 74
Plotting Tools
plottools Figure Palette gurepalette Plot Browser plotbrowser Property Editor propertyeditor
PsiPhiETC (www.psiphi.in)
January 1, 2012
46 / 74
subplot(m,n,p)
PsiPhiETC (www.psiphi.in)
January 1, 2012
47 / 74
Figure Palette Workspace Variables Select Variable Right click for plot catalog
PsiPhiETC (www.psiphi.in)
January 1, 2012
48 / 74
PsiPhiETC (www.psiphi.in)
January 1, 2012
49 / 74
Plot Browser
Displays all plot objects Select Plot Object Change Object Properties Deselect Plot Object Add Data
PsiPhiETC (www.psiphi.in)
January 1, 2012
50 / 74
Property Editor
Enable Edit Plot Select Object Go to Property Editor Changing Properties More Properties Context Menu
PsiPhiETC (www.psiphi.in)
January 1, 2012
51 / 74
Printing
File > Print Preview Figure Placement on Page, Paper Size and Orientation etc Line and Text Properties Color etc
PsiPhiETC (www.psiphi.in)
January 1, 2012
52 / 74
Exporting
PsiPhiETC (www.psiphi.in)
January 1, 2012
53 / 74
Saving
PsiPhiETC (www.psiphi.in)
January 1, 2012
54 / 74
Publishing Report
Introduction
Create a script le Divide script into code cells Insert Text Markup for formatting Edit Publish Conguration Publish
PsiPhiETC (www.psiphi.in)
January 1, 2012
55 / 74
Publishing Report
Code Cells
1 2 3 4
Open MATLAB editor Enable Cell mode Write Script Divide Script into Cells by %% Color change and cell separation line Can evaluate individual cell
PsiPhiETC (www.psiphi.in)
January 1, 2012
56 / 74
Publishing Report
Dened in rst code cell, starting from 1st line %% Document Title % Introduction % Introduction Must put %% after introduction Contents
1 2 3 4
PsiPhiETC (www.psiphi.in)
January 1, 2012
57 / 74
Publishing Report
New cell in existing section %% New cell that starts new section %% Section Title New section in existing cell %%% Section Title
1 2 3 4 5
%% New Section % introduction %% % Cell in Existing Section %%% New Section in ... Existing Cell
PsiPhiETC (www.psiphi.in)
January 1, 2012
58 / 74
Publishing Report
Numbered List
# Item 1 # Item 2
%% Other Text Markup % *bold text* % _italic text_ % | monospace text | % % * Item 1 % * Item 2 % % # Item 1 % # Item 2 % % <www.psiphi.in>
PsiPhiETC (www.psiphi.in)
January 1, 2012
59 / 74
Publishing Report
1 2 3
ei
+ 1 = 0 $$
PsiPhiETC (www.psiphi.in)
January 1, 2012
60 / 74
Publishing Report
Conguration
Output Settings
Output File format : HTML, PDF, DOC, PPT Output File Folder
Figure Setting
Image Format Image Size
Code Setting
Include Code Max number of lines
PsiPhiETC (www.psiphi.in)
Publishing Report
Displaying Results
Command Window o/p: No ; disp display the result sprintf is useful for formatted o/p
1 2 3 4
5 6 7
%% Displaying Output phi=1.618; PHI=(1+sqrt(5))/2; s=sprintf('phi=%5.3f, ... PHI=%10.8f',phi,PHI); disp(s); disp(PHI); phi
PsiPhiETC (www.psiphi.in)
January 1, 2012
62 / 74
Publishing Report
Example File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
%% Document Title % Introductory text %% Section % Section introduction %% Other Text Markup % *bold text* , _italic text_ , |monospace text| % <www.psiphi.in> %% More Text Markup % The TeX equations can be inserted like: % $$\phi=\frac{1+\sqrt{5}}{2}$$ %% Displaying Output phi=1.618; PHI=(1+sqrt(5))/2; s=sprintf('phi=%5.3f, PHI=%10.8f',phi,PHI); disp(s); disp(PHI); phi %% Plot theta=linspace(0,10*pi,200); r=exp(-theta/10); polar(theta,r);
Getting Started with MATLAB January 1, 2012 63 / 74
PsiPhiETC (www.psiphi.in)
Building GUI
Building GUI
Graphical Display for Performing Tasks Interactively Events callback (function, string) Interactive GUI Construction (GUIDE) Programmatic GUI Construction
PsiPhiETC (www.psiphi.in)
January 1, 2012
64 / 74
Building GUI
GUIDE
guide Getting Help GUIDE Layout Editor File > Preference > GUIDE > Show Names in Component palette > OK GUI Figure Size > Click and Drag Corner Creating Components
Axes Push Button Static Text Pop-up Menu
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 65 / 74
Building GUI
PsiPhiETC (www.psiphi.in)
January 1, 2012
66 / 74
Building GUI
Save SimpleGui
PsiPhiETC (www.psiphi.in)
January 1, 2012
67 / 74
Building GUI
Generating Data to Plot Programming The Popup Menu: Context Menu, View Callback Programming The Push Button: Context Menu, View Callback Save and Run GUI
PsiPhiETC (www.psiphi.in)
January 1, 2012
68 / 74
Simulink
Simulink
Dynamic System Modeling : Comprehensive block library of sources, sink, linear and nonlinear components, connectors etc Simulation : Wide choice of Integration Method Analysis: Linearization, MATLAB
PsiPhiETC (www.psiphi.in)
January 1, 2012
69 / 74
User Interface
User Interface
simulink or Simulink Library Browser - Commonly Used Blocks - Continuous (Derivative, Integrator, Transfer Function) - Math Operations (Gain, Sum) - Sources (sine wave, step) - Sinks (Scope, To Workspace) - Routing (Mux) Simulink Model Window - Simulation (Start, Conguration) - save, print
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 70 / 74
sin d
Simulink >File > New > Model > Save Drag from Library to Model Window
- Source > Sine Wave - Sink > Scope - Continuous > Integrator - Signal Routing > Mux
Connect blocks - Select 1st > hold Ctrl > Select 2nd - Similar way for branching Simulation: Conguration, Start Scope: Zoom, Export Data
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 71 / 74
Drag Components to model window To Rotate: Ctrl+R, To Flip: Ctrl+F Gain Parameters by double click More input to Sum Block Connect Components Simout for variables to Workspace Under damped, overdamped See variables in workspace sim command
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 72 / 74
x=
Drag components to Model Window Connect Them Double click transfer function block for parameter setting Double click save output to le block and set le path/name Run simulation Load mat le and plot data
PsiPhiETC (www.psiphi.in)
January 1, 2012
73 / 74
V (s) =
1 s
1 1 U(s) V (s) RC RC
Drag components to Model Window Connect Components Set parameters for various components Play with Conguration (Solver etc.) Simulation See results in scope
PsiPhiETC (www.psiphi.in)
January 1, 2012
74 / 74