getting started with matlab: slides
DESCRIPTION
These slides were made for introductory course on Getting Started with MATLAB. The course includes interactive computations, programming, graphics, simulink and GUI development. The course notes and slides may be downloaded from www.psiphi.in. See this website for updates and course schedule.TRANSCRIPT
Getting Started with MATLAB
PsiPhiETC
www.psiphi.in
January 1, 2012
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 1 / 74
Motivation
Why are you interested in MATLAB?
Driven byPresent AssignmentCuriosityUrge for Value Addition
Reason
Belief
Action Reward
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 2 / 74
Motivation
What is MATLAB?
MATrix LABoratoryHigh-performance scientific computationMATLAB System Integrates
1 Computation2 Visualization3 Programming
in an easy-to-use environmentMATLAB System Consists of
1 Desktop Tools and Dev Environment2 Mathematical Functions Library3 Programming4 Graphics5 External Interface
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 3 / 74
Motivation
Features of MATLAB!
Library of Mathematical FunctionsInteractive Computations throughCommand WindowProgramming for Complex ProblemsGraphics for Data Analysis andVisualizationGraphical User Interface (GUIDE)Specialized Toolboxes (Simulink)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 4 / 74
Motivation
Course Contents
# Topic Reference1 Introduction RP Ch1&22 Getting Started RP Ch23 Interactive Computation RP Ch34 Programming and Scripts RP Ch45 Programming and Functions RP Ch46 Graphics-1 RP Ch67 Graphics-2 Notes8 GUIDE & Simulink Notes
No Promise, only Opportunity! No Teaching, only Learning!
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 5 / 74
Motivation
Installation
Available for all major computingplatforms (Windows, Unix, Mac)World Wide Web:http://www.mathworks.com
Student and Professional VersionsRead the installation instructionscarefullyCheck Installation
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 6 / 74
Motivation
Desktop Tools & Development Environment
Menu [Desktop Tools (Layout), Help Browser], Editor, Current Directory [pwd,ls, window, M-Lint], Command Window [x=1, Workspace, x+1, ans], CommandHistory [Selection, Execution], Docking, Start, Ref:GSG-Ch7
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 7 / 74
Motivation
Ways to Get Help!
Extensive and excellentdocumentationHelp Browser
DemosSearch
Commands:lookfor ’string’help topicwhich topic
edit, H1 Line, Help, Code
1 >> lookfor mean2 >> help mean3 >> which mean4 >> edit mean
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 8 / 74
Motivation
Some General Commands
clc clears command windowclf clears figureclear: multiple variable, all variablescd change directorydir show directory contentspath [pwd, directories in path]copyfile copies filesmkdir make directorydate display datequit quit matlabdiary records the sessionsmart recall
1 >> diary2 >> pwd3 >> clc4 >> x=2;y=3;5 >> clear x6 >> clear all
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 9 / 74
Motivation
Vectors and Scalars
Variable Namesrow vec ( [], col sep), col vec(row sep)’, . . . , ;a : ∆ : blinspace(a,b,n)+, -, cross, dot, .* , ./, .^sin, cos, log, sqrtformat
1 >> rv=[1,2,3]2 >> cv=[1;2;3]3 >> v1=1:1:34 >> v2=linspace(1,3,3)5 >> v3=v1'6 >> v4=v1+v27 >> v5=v1.*v28 >> v6=sqrt(v1)9 >> format long e
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 10 / 74
Motivation
Simple Plots
plot (x,y)axis tight | equalxlabel (’string’)ylabel (’string’)title (’string’)grid on | off
1 x=linspace(0,2*pi,100);2 y=sin(x);3 plot(x,y);4 xlabel('x');5 ylabel('sin(x)');6 title('x vs sin(x)');7 axis tight;grid on;
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 11 / 74
Motivation
MATLAB Editor
Menu BarTool BarEditing SpaceLine NumberCode AnalysisMessageDocument BarStatus BarExecution andDebugging
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 12 / 74
Motivation
MATLAB Script
% for commentsH1 Line, HelpValid MATLABcommands andexpressionsComment %, KeywordsSavingExecution
1 % Script to find triangle area2 % The help for ScriptExample.m3
4 base=2; %triangle base5 height=1; %triangle height6 Area=(1/2)*base*height;
1 >> lookfor triangle2 >> help ScriptExample3 >> ScriptExample4 >> base5 >> height6 >> Area7 >> clear all
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 13 / 74
Motivation
MATLAB Functions
function[argout]=FN(argin)H1 Line% for commentsSavingexist (FN)argin pass by valuevariable are local
1 function [A]=FunctionExample(b,h)2 % FunctionExample for triangle area3 % The help for FunctionExample.m4 % Syntax A=FunctionExample(b,h)5
6 A=(1/2)*b*h;
1 >> base=2;height=1;2 >> Area=FunctionExample(base,height);3 >> b4 >> h5 >> A6 >> Area
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 14 / 74
Interactive Computations
Matrix Creation?
Enclosed within square bracket []Entered row wiseColumn Separator: space or ,Row Separator: ;. . . (ellipsis) is used for continuation
1 >> A=[1, 2, 3; 4, ...5, 6]
2 A =3 1 2 34 4 5 6
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 15 / 74
Interactive Computations
Matrix Indexing
A(i,j)=aij
size(A)=[m,n]
A(m1 : m2,n1 : n2) =
am1n1 . . . am1n2...
......
am2n1 . . . am2n2
A(:,k:end)
1 >> A=[1,2,3;...2 4,5,6]3 >> size(A)4 >> A(2,3)5 >> A(1:2,2:3)6 >> A(2,2:end)7 >> A(:,2:end)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 16 / 74
Interactive Computations
Matrix Manipulation
Element: A(i,j)=aij
Row: A(m,:)=v1×n
Column: A(:,n)=vm×1
Submatrix: A(m1 : m2,n1 : n2) =B(m2−m1)×(n2−n1)
Appending: A=[A, vm×1], A=[A; v1×n]Deleting: A(m,:)=[], A(:,n)=[]eye(m,n), zeros(m,n), ones(m,n),magic(n)
1 >>A=[1,2,3;4,5,6];2 >>A(1,2)=9;3 >>A(2,:)=[9,9,9]4 >>A(:,3)=[9;9]5 >>A(1:2,2:3)=[9,9;9,9]6 >>A(3,:)=[9,9,9];7 >>A(:,4)=[9;9;9];8 >>A(3,:)=[]9 >>A(:,4)=[]
10 >>eye(3)11 >>zeros(3)12 >>ones(3)13 >>magic(3)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 17 / 74
Interactive Computations
Matrix Operations
Arithmetic: +, -, *, /, ^Relational: <, >, <=, >=, ==, ∼=
Logical Operations: &, |, NOT ∼Logical Functions: all, any, exists,isempty, isinf, isnan
1 >> A=eye(2,2)2 >> B=ones(2,2)3 >> C=A*B4 >> R1=A<B5 >> R2=A==B6 >> R3=A 6=B7 >> L1=A&B8 >> L2=A|B9 >> F1=all(A)
10 >> F2=any(A)11 >> F3=isempty(A)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 18 / 74
Interactive Computations
Elementary Maths Functions
Trigonometric: sin , asin, . . .Exponential: exp , log, . . .Algebraic: sqrt, nthroot, . . .Complex: abs, angle, conj, img, realRound-off: floor, ceil, fix, mod, remMatrix: expm, sqrtm
1 >> sin(pi/6)2 >> exp(1)3 >> sqrt(2)4 >> z=1+i5 >> abs(z)6 >> angle(z)7 >> floor(1.9)8 >> ceil(1.1)9 >> A=ones(2,2)
10 >> expm(A)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 19 / 74
Interactive Computations
Character Strings
Single Quote: ’string’Manipulating stringevalnum2str, str2numlower, upperstrcmp, strncmpstrcat, findstr
1 >> s='Hello World'2 >> s(2)='E'3 >> eval('x=2*3')4 >> y='2.3'5 >> zn=str2num(y)6 >> zs=num2str(x)7 >> s1=lower(s)8 >> s2=strcat(s,s1)9 >> strcmpi('Hello','hello')
10 >> findstr(s,'W')
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 20 / 74
Interactive Computations
Saving and Loading Data
matlab.matsavesave (’fn’,’vn’)loadload datafile.txtd=load (’datafile.txt’)
1 >> x=linspace(0,2*pi,10)2 >> y=sin(x)3 >> save4 >> clear all5 >> load6 >> save('myfile','x')7 >> clear all8 >> load myfile9 >> load datafile.txt
10 >> d=load('datafile.txt')
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 21 / 74
Programming in MATLAB
Script Files
.m file containing validcommandsName shall starts with a letterand can have letters, digitsand _Avoid clash with names ofbuilt-in function (exist(’fn’))Variable Name 6= File NameWorks on global workspacevariablesUse of clear all
1 % solvex.m (Ref: RP)2 % 5 x1+2r x2+r x3=23 % 3 x1+6 x2+(2r-1) x3=34 % 2 x1+(r-1) x2+3r x3=55 A=[5, 2*r,r;3, 6, 2*r-1; ...
2, r-1, 3*r];6 b=[2;3;5];7 x=A\b
1 r=1;2 solvex
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 22 / 74
Programming in MATLAB
Function Files
function[argout] =FunctionName (argin)Local VariablesPass-by valueReadability: H1, helpModularity: subfunctionRobustness: nargin,error(‘message’)Expandability: varargin
1 function [det_A, x]=solvexf(r)2 % SOLVEXF solves eqn with par r3 % Function file solvexf.m4 % To call this function, type:5 % [det_A,x]=solvexf(r)6 % r is i/p and det_A & x are o/p7
8 A=[5, 2*r, r; 3,6, 2*r-1; 2, ...r-1, 3*r];
9 b=[2;3;5];10 det_A=det(A);11 x=A\b;
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 23 / 74
Programming in MATLAB
Control Flow: if-elseif-else
1 if expression2 statements3 elseif expression4 statements5 else6 statements7 end
1 if I == J2 A(I,J) = 2;3 elseif abs(I-J) == 14 A(I,J) = -1;5 else6 A(I,J) = 0;7 end
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 24 / 74
Programming in MATLAB
Control Flow: for loops
1 for variable = expression2 statement(s)3 end
1 sum=0;2 for i=1:1003 sum=sum+i;4 end
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 25 / 74
Programming in MATLAB
Control Flow: while loops
1 while expression2 statements3 end
Example of while loop,
1 v=1; num=1; i=1;2 while (num≤4096)3 v=[v;num];4 i=i+1;5 num=2^i;6 end7 v
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 26 / 74
Programming in MATLAB
Control Flow: switch-case-otherwise
1 switch flag2 case val1 block 1 computation3 case val2 block 2 computation4 otherwise last block computation5 end
1 color= input('color= ','s');2 switch color3 case 'red' c=[1, 0, 0];4 case 'green' c=[0, 1, 0];5 case 'blue' c=[0, 0, 1];6 otherwise error('invalid')7 end
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 27 / 74
Programming in MATLAB
break, continue and return
break terminates for or while loopcontinue pass control to the nextiteration of for or while loopreturn return to invoking function
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 28 / 74
Programming in MATLAB
Interactive Input: input, keyboard and pause
Age=input(‘Age plz?’)Name=input(‘Name plz?’, ’s’)script/function keyboard k �statements returnpause, pause(n)
1 Age=input('Age Plz?');2 Name=input('Name Plz?','s');3 keyboard;4 >> Age5 >> Name6 k>> Age=217 k>> Name='ABC'8 k>> return9 pause(10)
10 disp(Age)11 disp(Name)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 29 / 74
Programming in MATLAB
Input/Output
fid = fopen (fn, r|w|a)fclose (fid)fprintf (fid, format, x)x=fscanf (fid, format)sscanf, sprintffgets, fgetl
1 fid=fopen('a.txt','w');2 fprintf(fid,'pi=%10.8f \n',pi);3 s=sprintf('e=%10.8f\n',exp(1));4 fprintf(fid,s);5 fclose(fid);6 fid=fopen('a.txt','r');7 s1=fgets(fid);8 s2=fgetl(fid);9 PI=sscanf(s1,'pi=%f');
10 E=sscanf(s2,'e=%f');
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 30 / 74
Creating Graphics Programmatically
Figure
h=figureh=gcffigure(h)Edit > Figure PropertiesProperty Editor > Figure
Name: ’string’Color: [r,g,b], (r ,g,b) ∈ [0,1]NumberTitle: {on}|off
More PropertiesMenubar: {figure}|nonePosition: [x,y,w,h]
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 31 / 74
Creating Graphics Programmatically
Setting Figure Properties
h=figure or h=gcfget (h) -> ‘PropertyName’,PropertyValueget (h) -> ‘PropertyName’{PropertyValueActive} |PropertyValueOptionalset (h, ’PropertyName’,PropertyValue)
1 set (h,'Name','myName')2 set (h,'NumberTitle','off')3 set (h,'Menubar','none')4 set (h,'Color',[1,0,0])5 set (h, 'Position', ...
[500,200,400,300])
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 32 / 74
Creating Graphics Programmatically
Axes
axesa=axes –> Handle aa=axes(’PropertyName’,PropertyValue)Important Properties:
ColorFontSize,FontWeight, . . .LineWidth, . . .XGrid, YGridXLim, YLimXTick, YTickXTickLabel,YTickLabel
1 a=axes;2 get(a);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 33 / 74
Creating Graphics Programmatically
Setting Axes Properties
p=axes()get (p)set (p)set (p,’PropertyName’,PropertyValue)
1 set (a, 'Color' , [1,1,0])2 set (a, 'LineWidth' , 3)3 set (a, 'XGrid' , 'on')4 set (a, 'YLim' , [-1, 1])5 set (a, 'XTick' , [0.2,0.6,0.9])6 set (a,'XTickLabel',{0.2,'six',0.9} )7 set (a, 'YTick' , [0.3,0.6,0.9])8 set (a,'YTickLabel',{'y1',0.6,'y_2'} )
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 34 / 74
Creating Graphics Programmatically
Plot
plot (y)plot (x,y)plot (x,y,’LineSpecs’)
Color: r,g,b,. . .LineStyle: -, –, . . .MarkerStyle: *, + . . .
plot (x,y, ’LineSpecs’,’PropertyName’,PropertyValue)LineStyle, LineWidth, Marker,
MarkerSize
1 x=0:10;2 y=x.^2;3 plot(x,y,'r-*', ...
'Linewidth', 3,...'MarkerSize', 12)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 35 / 74
Creating Graphics Programmatically
Setting Plot Properties
p=plot (x,y)get (p)set (p)set (p, ’PropertyName’,PropertyValue)
1 x=0:10;y=x.^2;2 p=plot(x,y);3 set(p , 'Color' , [0,1,0]);4 set(p , 'LineWidth' , 3);5 set(p , 'LineStyle' , '-');6 set(p , 'Marker' , 'o');7 set(p , 'MarkerSize' , 12);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 36 / 74
Creating Graphics Programmatically
Overlay Plot
plot (x1,y1,x2,y2)plot ( x1,y1,’LS1’, x2,y2,’LS2’)plot (x1,y1,’LS’, ’PropName’,PropValue)hold onplot (x2,y2, ’LS’, ’PropName’,PropValue)hold off;line (x, y, ’PropName’,PropValue)
1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x2.^3;3 p1=plot(x1,y1,'r-*');4 set(p1,'Linewidth',3);5 hold on;6 p2=plot(x2,y2,'b:o');7 set(p2,'Linewidth',4);8 hold off; grid on;9 set(gca,'Linewidth',2);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 37 / 74
Creating Graphics Programmatically
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)
1 x=0:10;y=x.^2;plot(x,y);2 t=text(1,20, 'P(1,20)');3 set(t,'FontSize',14);4 [x1,y1]=ginput(1);5 t1=text(x1,y1,'(x1,y1)')6 gtext('gtext','FontSize',14);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 38 / 74
Creating Graphics Programmatically
Axis
axis ([xmin, xmax, ymin, ymax])axis equalaxis squareaxis tightaxis normal
Semi Control of Axis:axis (xmin,inf,-inf,ymax)
1 x=linspace(0,2*pi,100);2 y=sin(x);3 plot(x,y);4 axis([0,2*pi,-1,1]);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 39 / 74
Creating Graphics Programmatically
Legend
legend (’string’)legend (’string1’,’string2’,. . . )legend (’string1’,’string2’,. . . ,’PropertyName’,PropertyValue)
1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x1.^3;3 p=plot(x1,y1,'r',x2,y2,'g');4 set(p,'Linewidth',4);5 l=legend('data x1-y1', ...
'data x2-y2');6 set(l,'Location','NorthWest');
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 40 / 74
Creating Graphics Programmatically
Subplot
subplot (m,n,p)m: Number of rowsn: Number of columnsp: plot number
1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x2.^3;3 subplot (1,2,1);4 plot (x1,y1,'g','Linewidth',3);5 subplot (1,2,2);6 plot(x2,y2,'r','Linewidth',3);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 41 / 74
Creating Graphics Programmatically
Findobj
h=findobjh=findobj (’PropertyName’,’PropertyValue’)h=findobj (ObjectHandles,’PropertyName’,’PropertyValue’)
1 x1=-5:5; y1=x1.^2;2 x2=-5:5; y2=x2.^3;3 plot (x1,y1,'r',x2,y2,'g');4 h1=findobj('Color','r');5 set(h1,'Linewidth',3);6 h2=findobj('Color','g');7 set(h2,'Color','b','Linewidth',3);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 42 / 74
Creating Graphics Interactively
Graphics Objects Hierarchy
FigureAxesPlot ObjectsAnnotation Objects
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 43 / 74
Creating Graphics Interactively
Plotting Process
Creating GraphExploring DataEditing Graph ComponentsAnnotation GraphsPrinting and Exporting GraphsAdding and Removing ContentsSaving Graph for Reuse
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 44 / 74
Creating Graphics Interactively
Figure Tools
ZoomPanData CursorBasic FittingData Statistics
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 45 / 74
Creating Graphics Interactively
Plotting Tools
plottoolsFigure PalettefigurepalettePlot BrowserplotbrowserProperty Editorpropertyeditor
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 46 / 74
Creating Graphics Interactively
Figure Palette: New Subplots
subplot(m,n,p)
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 47 / 74
Creating Graphics Interactively
Figure Palette: Variables and Plot Catalog
Figure PaletteWorkspace VariablesSelect VariableRight click for plot catalog
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 48 / 74
Creating Graphics Interactively
Figure Palette: Annotations
LineArrowDouble ArrowText BoxArrow Box. . .
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 49 / 74
Creating Graphics Interactively
Plot Browser
Displays all plot objectsSelect Plot ObjectChange ObjectPropertiesDeselect Plot ObjectAdd Data
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 50 / 74
Creating Graphics Interactively
Property Editor
Enable Edit PlotSelect ObjectGo to Property EditorChanging PropertiesMore PropertiesContext Menu
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 51 / 74
Creating Graphics Interactively
Printing
File > Print PreviewFigure Placement onPage, Paper Size andOrientation etcLine and TextPropertiesColor etc
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 52 / 74
Creating Graphics Interactively
Exporting
File > Export SetupChange PropertiesExportsaveas
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 53 / 74
Creating Graphics Interactively
Saving
File > Saveas.fig.m (function)saveas
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 54 / 74
Publishing Report
Introduction
Formatted report in HTML, PDF, LATEX, MS Word or MS PowerPointSteps Involved
Create a script fileDivide script into ‘code cells’Insert Text Markup for formattingEdit Publish ConfigurationPublish
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 55 / 74
Publishing Report
Code Cells
Open MATLAB editorEnable Cell modeWrite ScriptDivide Script into Cells by %%Color change and cellseparation lineCan evaluate individual cell
1 %% Create vectors2 theta=linspace(0,10*pi,200);3 r=exp(-theta/10);4 %% Plot using polar plot5 polar(theta,r);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 56 / 74
Publishing Report
Document Title and Introduction
Defined in first code cell, starting from1st line%% Document Title% Introduction% IntroductionMust put %% after introductionContents
1 %% This is the Title2 % Introductory text3 % Introductory text4 %%
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 57 / 74
Publishing Report
Section and Section Titles
New cell in existing section%%New cell that starts newsection %% Section TitleNew section in existing cell%%% Section Title
1 %% New Section2 % introduction3 %%4 % Cell in Existing Section5 %%% New Section in ...
Existing Cell
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 58 / 74
Publishing Report
Other Text Markup
*bold text *_ italic text_|monospace text|Bulleted List
* Item 1* Item 2
Numbered List# Item 1# Item 2
Hyperlinked Text < www.psiphi.in>
1 %% Other Text Markup2 % *bold text*3 % _italic text_4 % | monospace text |5 %6 % * Item 17 % * Item 28 %9 % # Item 1
10 % # Item 211 %12 % <www.psiphi.in>
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 59 / 74
Publishing Report
Other Text Markup. . .
Including Image <<IMAGE.JPG>>LATEX Markup% <latex>% LATEX stuff% </latex>TEX Equations $$ eπi + 1 = 0 $$HTML Markup
1 %% More Text Markup2 % <IMAGE.JPG>3 % $$ e^{\pi i}+1=0 $$
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 60 / 74
Publishing Report
Configuration
Output SettingsOutput File format : HTML, PDF,DOC, PPTOutput File Folder
Figure SettingImage FormatImage Size
Code SettingInclude CodeMax number of lines
publish for changing configurationfrom script
PDFHTMLDoc
FigureCode
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 61 / 74
Publishing Report
Displaying Results
Command Window o/p:No ;disp display the resultsprintf is useful forformatted o/p
1 %% Displaying Output2 phi=1.618;3 PHI=(1+sqrt(5))/2;4 s=sprintf('phi=%5.3f, ...
PHI=%10.8f',phi,PHI);5 disp(s);6 disp(PHI);7 phi
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 62 / 74
Publishing Report
Example File
1 %% Document Title2 % Introductory text3 %% Section4 % Section introduction5 %% Other Text Markup6 % *bold text* , _italic text_ , |monospace text|7 % <www.psiphi.in>8 %% More Text Markup9 % The TeX equations can be inserted like:
10 % $$\phi=\frac{1+\sqrt{5}}{2}$$11 %% Displaying Output12 phi=1.618; PHI=(1+sqrt(5))/2;13 s=sprintf('phi=%5.3f, PHI=%10.8f',phi,PHI);14 disp(s); disp(PHI); phi15 %% Plot16 theta=linspace(0,10*pi,200);17 r=exp(-theta/10); polar(theta,r);
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 63 / 74
Building GUI
Building GUI
Graphical Display forPerforming Tasks InteractivelyEvents→ callback (function,string)Interactive GUI Construction(GUIDE)Programmatic GUIConstruction
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 64 / 74
Building GUI
GUIDE
guideGetting HelpGUIDE Layout EditorFile > Preference > GUIDE >Show Names in Componentpalette > OKGUI Figure Size > Click andDrag CornerCreating Components
AxesPush ButtonStatic TextPop-up Menu
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 65 / 74
Building GUI
Creating Simple GUI
simple_ guiAdding Components
AxesThree Push ButtonStatic TextPop-up Menu
Align Pushbuttons > Tools >Align Objects
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 66 / 74
Building GUI
Creating Simple GUI. . .
Adding Text To ComponentsView > Property Inspector >Push Button: Select PushButton > String > Change itPopup Menu : Select PopupMenu > String >Components in differentlinesStatic Text: Select > String> Change it
Save SimpleGui
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 67 / 74
Building GUI
Programming Simple GUI
Generating Data to PlotProgramming The PopupMenu: Context Menu, ViewCallbackProgramming The PushButton: Context Menu, ViewCallbackSave and Run GUI
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 68 / 74
Simulink
Simulink
Dynamic SystemModeling : Comprehensive block library of sources,sink, linear and nonlinear components, connectorsetcSimulation : Wide choice of Integration MethodAnalysis: Linearization, MATLAB
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 69 / 74
User Interface
User Interface
simulink orSimulink 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,
Configuration)- save, printPsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 70 / 74
Example 1: Sine wave and its Integration
Example 1: Sine wave and its Integration
Display: sin(t) ,∫ t
t0sin τ dτ
Simulink >File > New > Model >SaveDrag 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: Configuration, StartScope: Zoom, Export Data
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 71 / 74
Example: Spring Mass System (Direct Approach)
Example: Spring Mass System (Direct Approach)
x =1m
(f (t)− cx − kx)
Drag Components to model windowTo Rotate: Ctrl+R, To Flip: Ctrl+FGain Parameters by double clickMore input to Sum BlockConnect ComponentsSimout for variables to WorkspaceUnder damped, overdampedSee variables in workspacesim command
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 72 / 74
Example: Spring Mass System (Transfer Function)
Example: Spring Mass System (Transfer Function)
x =1m
(f (t)− cx − kx)
Drag components to Model WindowConnect ThemDouble click transfer function block forparameter settingDouble click save output to file blockand set file path/nameRun simulationLoad mat file and plot data
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 73 / 74
Example: Capacitor Charging
Example: Capacitor Charging
V (s) =1s
(1
RCU(s)− 1
RCV (s)
)
Drag components to Model WindowConnect ComponentsSet parameters for variouscomponentsPlay with Configuration (Solver etc.)SimulationSee results in scope
PsiPhiETC (www.psiphi.in) Getting Started with MATLAB January 1, 2012 74 / 74