SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
6.094
Introduction to programming in MATLAB
Danilo Ơćepanović
IAP 2010
Lecture 2: Visualization and Programming
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
User-defined Functions
‱ Functions look exactly like scripts, but for ONE difference
Functions must have a function declaration
Help file
Function declaration
InputsOutputs
Courtesy of The MathWorks, Inc. Used with permission.
User-defined Functions
‱ Some comments about the function declaration
‱ No need for return: MATLAB 'returns' the variables whose
names match those in the function declaration
‱ Variable scope: Any variables created within the function
but not returned disappear after the function stops running
function [x, y, z] = funName(in1, in2)
Must have the reserved
word: function
Function name should
match MATLAB file
name
If more than one output,
must be in brackets
Inputs must be specified
Functions: overloading
‱ We're familiar with
» zeros
» size
» length
» sum
‱ Look at the help file for size by typing
» help size
‱ The help file describes several ways to invoke the function
D = SIZE(X)
[M,N] = SIZE(X)
[M1,M2,M3,...,MN] = SIZE(X)
M = SIZE(X,DIM)
Functions: overloading
‱ MATLAB functions are generally overloaded
Can take a variable number of inputs
Can return a variable number of outputs
‱ What would the following commands return:
» a=zeros(2,4,8); %n-dimensional matrices are OK
» D=size(a)
» [m,n]=size(a)
» [x,y,z]=size(a)
» m2=size(a,2)
‱ You can overload your own functions by having variable
input and output arguments (see varargin, nargin,
varargout, nargout)
Functions: Excercise
‱ Write a function with the following declaration:
function plotSin(f1)
‱ In the function, plot a sin wave with frequency f1, on the
range [0,2π]:
‱ To get good sampling, use 16 points per period.
( )1sin f x
0 1 2 3 4 5 6 7
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Relational Operators
‱ MATLAB uses mostly standard relational operators
equal ==
not equal ~=
greater than >
less than <
greater or equal >=
less or equal <=
‱ Logical operators elementwise short-circuit (scalars)
And & &&
Or | ||
Not ~
Xor xor
All true all
Any true any
‱ Boolean values: zero is false, nonzero is true
‱ See help . for a detailed list of operators
if/else/elseif
‱ Basic flow-control, common to all languages
‱ MATLAB syntax is somewhat unique
IF
if cond
commands
end
ELSE
if cond
commands1
else
commands2
end
ELSEIF
if cond1
commands1
elseif cond2
commands2
else
commands3
end
‱ No need for parentheses: command blocks are between
reserved words
Conditional statement:
evaluates to true or false
for
‱ for loops: use for a known number of iterations
‱ MATLAB syntax:
for n=1:100
commands
end
‱ The loop variable
Is defined as a vector
Is a scalar within the command block
Does not have to have consecutive values (but it's usually
cleaner if they're consecutive)
‱ The command block
Anything between the for line and the end
Loop variable
Command block
while
‱ The while is like a more general for loop:
Don't need to know number of iterations
‱ The command block will execute while the conditional
expression is true
‱ Beware of infinite loops!
WHILE
while cond
commands
end
Exercise: Conditionals
‱ Modify your plotSin(f1) function to take two inputs: plotSin(f1,f2)
‱ If the number of input arguments is 1, execute the plot command
you wrote before. Otherwise, display the line 'Two inputs were
given'
‱ Hint: the number of input arguments are in the built-in variable
nargin
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Plot Options
‱ Can change the line color, marker style, and line style by
adding a string argument
» plot(x,y,’k.-’);
‱ Can plot without connecting the dots by omitting line style
argument
» plot(x,y,’.’)
‱ Look at help plot for a full list of colors, markers, and
linestyles
color marker line-style
Playing with the Plot
to select lines
and delete or
change
properties
to zoom in/out
to slide the plot
around
to see all plot
tools at once
Courtesy of The MathWorks, Inc. Used with permission.
Line and Marker Options
‱ Everything on a line can be customized
» plot(x,y,'--s','LineWidth',2,...
'Color', [1 0 0], ...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
‱ See doc line_props for a full list of
properties that can be specified
-4 -3 -2 -1 0 1 2 3 4
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
You can set colors by using
a vector of [R G B] values
or a predefined color
character like 'g', 'k', etc.
Cartesian Plots
‱ We have already seen the plot function
» x=-pi:pi/100:pi;
» y=cos(4*x).*sin(10*x).*exp(-abs(x));
» plot(x,y,'k-');
‱ The same syntax applies for semilog and loglog plots
» semilogx(x,y,'k');
» semilogy(y,'r.-');
» loglog(x,y);
‱ For example:
» x=0:100;
» semilogy(x,exp(x),'k.-');
0 10 20 30 40 50 60 70 80 90 100
10
0
10
10
10
20
10
30
10
40
10
50
-1
-0.5
0
0.5
1
-1
-0.5
0
0.5
1
-10
-5
0
5
10
3D Line Plots
‱ We can plot in 3 dimensions just as easily as in 2
» time=0:0.001:4*pi;
» x=sin(time);
» y=cos(time);
» z=time;
» plot3(x,y,z,'k','LineWidth',2);
» zlabel('Time');
‱ Use tools on figure to rotate it
‱ Can set limits on all 3 axes
» xlim, ylim, zlim
Axis Modes
‱ Built-in axis modes
» axis square
makes the current axis look like a box
» axis tight
fits axes to data
» axis equal
makes x and y scales the same
» axis xy
puts the origin in the bottom left corner (default for plots)
» axis ij
puts the origin in the top left corner (default for
matrices/images)
Multiple Plots in one Figure
‱ To have multiple axes in one figure
» subplot(2,3,1)
makes a figure with 2 rows and three columns of axes, and
activates the first axis for plotting
each axis can have labels, a legend, and a title
» subplot(2,3,4:6)
activating a range of axes fuses them into one
‱ To close existing figures
» close([1 3])
closes figures 1 and 3
» close all
closes all figures (useful in scripts/functions)
Copy/Paste Figures
‱ Figures can be pasted into other apps (word, ppt, etc)
‱ Edit copy options figure copy template
Change font sizes, line properties; presets for word and ppt
‱ Edit copy figure to copy figure
‱ Paste into document of interest
Courtesy of The MathWorks, Inc. Used with permission.
Saving Figures
‱ Figures can be saved in many formats. The common ones
are:
.fig preserves all
information
.bmp uncompressed
image
.eps high-quality
scaleable format
.pdf compressed
image
Courtesy of The MathWorks, Inc. Used with permission.
Advanced Plotting: Exercise
‱ Modify the plot command in your plotSin function to use
squares as markers and a dashed red line of thickness 2
as the line. Set the marker face color to be black
(properties are LineWidth, MarkerFaceColor)
‱ If there are 2 inputs, open a new figure with 2 axes, one on
top of the other (not side by side), and activate the top one
(subplot)
0 1 2 3 4 5 6 7
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0
0.2
0.4
0.6
0.8
1
plotSin(6) plotSin(1,2)
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Visualizing matrices
‱ Any matrix can be visualized as an image
» mat=reshape(1:10000,100,100);
» imagesc(mat);
» colorbar
‱ imagesc automatically scales the values to span the entire
colormap
‱ Can set limits for the color axis (analogous to xlim, ylim)
» caxis([3000 7000])
Colormaps
‱ You can change the colormap:
» imagesc(mat)
default map is jet
» colormap(gray)
» colormap(cool)
» colormap(hot(256))
‱ See help hot for a list
‱ Can define custom colormap
» map=zeros(256,3);
» map(:,2)=(0:255)/255;
» colormap(map);
Surface Plots
‱ It is more common to visualize surfaces in 3D
‱ Example:
‱ surf puts vertices at specified points in space x,y,z, and
connects all the vertices to make a surface
‱ The vertices can be denoted by matrices X,Y,Z
‱ How can we make these matrices
loop (DUMB)
built-in function: meshgrid
( ) ( ) ( )
[ ] [ ]
f x,y sin x cos y
x , ; y ,π π π π
=
∈ − ∈ −
2 4 6 8 10 12 14 16 18 20
2
4
6
8
10
12
14
16
18
20 -3
-2
-1
0
1
2
3
2 4 6 8 10 12 14 16 18 20
2
4
6
8
10
12
14
16
18
20 -3
-2
-1
0
1
2
3
surf
‱ Make the x and y vectors
» x=-pi:0.1:pi;
» y=-pi:0.1:pi;
‱ Use meshgrid to make matrices (this is the same as loop)
» [X,Y]=meshgrid(x,y);
‱ To get function values,
evaluate the matrices
» Z =sin(X).*cos(Y);
‱ Plot the surface
» surf(X,Y,Z)
» surf(x,y,Z);
surf Options
‱ See help surf for more options
‱ There are three types of surface shading
» shading faceted
» shading flat
» shading interp
‱ You can change colormaps
» colormap(gray)
contour
‱ You can make surfaces two-dimensional by using contour
» contour(X,Y,Z,'LineWidth',2)
takes same arguments as surf
color indicates height
can modify linestyle properties
can set colormap
» hold on
» mesh(X,Y,Z)
Exercise: 3-D Plots
‱ Modify plotSin to do the following:
‱ If two inputs are given, evaluate the following function:
‱ y should be just like x, but using f2. (use meshgrid to get
the X and Y matrices)
‱ In the top axis of your subplot, display an image of the Z
matrix. Display the colorbar and use a hot colormap. Set
the axis to xy (imagesc, colormap, colorbar, axis)
‱ In the bottom axis of the subplot, plot the 3-D surface of Z
(surf)
( ) ( )1 2sin sinZ f x f y= +
Specialized Plotting Functions
‱ MATLAB has a lot of specialized plotting functions
‱ polar-to make polar plots
» polar(0:0.01:2*pi,cos((0:0.01:2*pi)*2))
‱ bar-to make bar graphs
» bar(1:10,rand(1,10));
‱ quiver-to add velocity vectors to a plot
» [X,Y]=meshgrid(1:10,1:10);
» quiver(X,Y,rand(10),rand(10));
‱ stairs-plot piecewise constant functions
» stairs(1:10,rand(1,10));
‱ fill-draws and fills a polygon with specified vertices
» fill([0 1 0.5],[0 0 1],'r');
‱ see help on these functions for syntax
‱ doc specgraph – for a complete list
Outline
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Revisiting find
‱ find is a very important function
Returns indices of nonzero values
Can simplify code and help avoid loops
‱ Basic syntax: index=find(cond)
» x=rand(1,100);
» inds = find(x>0.4 & x<0.6);
‱ inds will contain the indices at which x has values between
0.4 and 0.6. This is what happens:
x>0.4 returns a vector with 1 where true and 0 where false
x<0.6 returns a similar vector
The & combines the two vectors using an and
The find returns the indices of the 1's
Example: Avoiding Loops
‱ Given x= sin(linspace(0,10*pi,100)), how many of the
entries are positive?
Using a loop and if/else
count=0;
for n=1:length(x)
if x(n)>0
count=count+1;
end
end
Being more clever
count=length(find(x>0));
length(x) Loop time Find time
100 0.01 0
10,000 0.1 0
100,000 0.22 0
1,000,000 1.5 0.04
‱ Avoid loops!
‱ Built-in functions will make it faster to write and execute
Efficient Code
‱ Avoid loops
This is referred to as vectorization
‱ Vectorized code is more efficient for MATLAB
‱ Use indexing and matrix operations to avoid loops
‱ For example, to sum up every two consecutive terms:
» a=rand(1,100);
» b=zeros(1,100);
» for n=1:100
» if n==1
» b(n)=a(n);
» else
» b(n)=a(n-1)+a(n);
» end
» end
Slow and complicated
» a=rand(1,100);
» b=[0 a(1:end-1)]+a;
Efficient and clean.
Can also do this using
conv
End of Lecture 2
(1) Functions
(2) Flow Control
(3) Line Plots
(4) Image/Surface Plots
(5) Vectorization
Vectorization makes
coding fun!
MIT OpenCourseWare
http://ocw.mit.edu
6.094 Introduction to MATLABÂź
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

Weitere Àhnliche Inhalte

Was ist angesagt?

Perm winter school 2014.01.31
Perm winter school 2014.01.31Perm winter school 2014.01.31
Perm winter school 2014.01.31Vyacheslav Arbuzov
 
Geometry Shader-based Bump Mapping Setup
Geometry Shader-based Bump Mapping SetupGeometry Shader-based Bump Mapping Setup
Geometry Shader-based Bump Mapping SetupMark Kilgard
 
CS 354 Graphics Math
CS 354 Graphics MathCS 354 Graphics Math
CS 354 Graphics MathMark Kilgard
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21Sangita Panchal
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlabneetirajsinh
 
Data Wrangling with dplyr and tidyr Cheat Sheet
Data Wrangling with dplyr and tidyr Cheat SheetData Wrangling with dplyr and tidyr Cheat Sheet
Data Wrangling with dplyr and tidyr Cheat SheetDr. Volkan OBAN
 
Java applet handouts
Java applet handoutsJava applet handouts
Java applet handoutsiamkim
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingMark Kilgard
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python PandasSangita Panchal
 
Output primitives computer graphics c version
Output primitives   computer graphics c versionOutput primitives   computer graphics c version
Output primitives computer graphics c versionMarwa Al-Rikaby
 
Surpac geological modelling 3
Surpac geological modelling 3Surpac geological modelling 3
Surpac geological modelling 3Adi Handarbeni
 
Introductory Digital Image Processing using Matlab, IIT Roorkee
Introductory Digital Image Processing using Matlab, IIT RoorkeeIntroductory Digital Image Processing using Matlab, IIT Roorkee
Introductory Digital Image Processing using Matlab, IIT RoorkeeVinayak Sahai
 
Image processing using matlab
Image processing using matlab Image processing using matlab
Image processing using matlab SangeethaSasi1
 
COMPUTER GRAPHICS
COMPUTER GRAPHICSCOMPUTER GRAPHICS
COMPUTER GRAPHICSJagan Raja
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 

Was ist angesagt? (20)

Perm winter school 2014.01.31
Perm winter school 2014.01.31Perm winter school 2014.01.31
Perm winter school 2014.01.31
 
Geometry Shader-based Bump Mapping Setup
Geometry Shader-based Bump Mapping SetupGeometry Shader-based Bump Mapping Setup
Geometry Shader-based Bump Mapping Setup
 
CS 354 Graphics Math
CS 354 Graphics MathCS 354 Graphics Math
CS 354 Graphics Math
 
Data Visualization 2020_21
Data Visualization 2020_21Data Visualization 2020_21
Data Visualization 2020_21
 
R graphics
R graphicsR graphics
R graphics
 
Image processing with matlab
Image processing with matlabImage processing with matlab
Image processing with matlab
 
Data Wrangling with dplyr and tidyr Cheat Sheet
Data Wrangling with dplyr and tidyr Cheat SheetData Wrangling with dplyr and tidyr Cheat Sheet
Data Wrangling with dplyr and tidyr Cheat Sheet
 
Java applet handouts
Java applet handoutsJava applet handouts
Java applet handouts
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
 
Seminar psu 20.10.2013
Seminar psu 20.10.2013Seminar psu 20.10.2013
Seminar psu 20.10.2013
 
CS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and CullingCS 354 Transformation, Clipping, and Culling
CS 354 Transformation, Clipping, and Culling
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python Pandas
 
Pandas Series
Pandas SeriesPandas Series
Pandas Series
 
Output primitives computer graphics c version
Output primitives   computer graphics c versionOutput primitives   computer graphics c version
Output primitives computer graphics c version
 
Surpac geological modelling 3
Surpac geological modelling 3Surpac geological modelling 3
Surpac geological modelling 3
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
Introductory Digital Image Processing using Matlab, IIT Roorkee
Introductory Digital Image Processing using Matlab, IIT RoorkeeIntroductory Digital Image Processing using Matlab, IIT Roorkee
Introductory Digital Image Processing using Matlab, IIT Roorkee
 
Image processing using matlab
Image processing using matlab Image processing using matlab
Image processing using matlab
 
COMPUTER GRAPHICS
COMPUTER GRAPHICSCOMPUTER GRAPHICS
COMPUTER GRAPHICS
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 

Andere mochten auch

Coursee
CourseeCoursee
CourseeAqua Pie
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)Retheesh Raj
 
Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Tribhuwan Pant
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlabAKANKSHA GUPTA
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming projectAssignmentpedia
 
Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06Aman kazmi
 
aem : Fourier series of Even and Odd Function
aem :  Fourier series of Even and Odd Functionaem :  Fourier series of Even and Odd Function
aem : Fourier series of Even and Odd FunctionSukhvinder Singh
 
MATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCRMATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCRGhanshyam Dusane
 
Licence plate recognition using matlab programming
Licence plate recognition using matlab programming Licence plate recognition using matlab programming
Licence plate recognition using matlab programming somchaturvedi
 
Product and service design
Product and service designProduct and service design
Product and service designGrace Falcis
 

Andere mochten auch (10)

Coursee
CourseeCoursee
Coursee
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Mit6 094 iap10_lec01
Mit6 094 iap10_lec01
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlab
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming project
 
Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06Lecture 19 matlab_script&function_files06
Lecture 19 matlab_script&function_files06
 
aem : Fourier series of Even and Odd Function
aem :  Fourier series of Even and Odd Functionaem :  Fourier series of Even and Odd Function
aem : Fourier series of Even and Odd Function
 
MATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCRMATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCR
 
Licence plate recognition using matlab programming
Licence plate recognition using matlab programming Licence plate recognition using matlab programming
Licence plate recognition using matlab programming
 
Product and service design
Product and service designProduct and service design
Product and service design
 

Ähnlich wie Lecture 02 visualization and programming

Matlab ch1 (6)
Matlab ch1 (6)Matlab ch1 (6)
Matlab ch1 (6)mohsinggg
 
Mit6 094 iap10_lec02
Mit6 094 iap10_lec02Mit6 094 iap10_lec02
Mit6 094 iap10_lec02Tribhuwan Pant
 
malab programming power point presentation
malab  programming power point presentationmalab  programming power point presentation
malab programming power point presentationrohitkuarm5667
 
Lecture1_computer vision-2023.pdf
Lecture1_computer vision-2023.pdfLecture1_computer vision-2023.pdf
Lecture1_computer vision-2023.pdfssuserff72e4
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plottingpink1710
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabKhulna University
 
Lecture_3.pptx
Lecture_3.pptxLecture_3.pptx
Lecture_3.pptxSungaleliYuen
 
Exploratory data analysis using r
Exploratory data analysis using rExploratory data analysis using r
Exploratory data analysis using rTahera Shaikh
 
Powerpointpresentation.c
Powerpointpresentation.cPowerpointpresentation.c
Powerpointpresentation.cMaqbool Ur Khan
 
Intro matlab and convolution islam
Intro matlab and convolution islamIntro matlab and convolution islam
Intro matlab and convolution islamIslam Alabbasy
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.pptSudhirNayak43
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.pptManasaChevula1
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functionsjoellivz
 
K10765 Matlab 3D Mesh Plots
K10765 Matlab 3D Mesh PlotsK10765 Matlab 3D Mesh Plots
K10765 Matlab 3D Mesh PlotsShraddhey Bhandari
 

Ähnlich wie Lecture 02 visualization and programming (20)

MATLAB PLOT.pdf
MATLAB PLOT.pdfMATLAB PLOT.pdf
MATLAB PLOT.pdf
 
Matlab ch1 (6)
Matlab ch1 (6)Matlab ch1 (6)
Matlab ch1 (6)
 
Mit6 094 iap10_lec02
Mit6 094 iap10_lec02Mit6 094 iap10_lec02
Mit6 094 iap10_lec02
 
R training5
R training5R training5
R training5
 
MATLAB & Image Processing
MATLAB & Image ProcessingMATLAB & Image Processing
MATLAB & Image Processing
 
malab programming power point presentation
malab  programming power point presentationmalab  programming power point presentation
malab programming power point presentation
 
Lecture1_computer vision-2023.pdf
Lecture1_computer vision-2023.pdfLecture1_computer vision-2023.pdf
Lecture1_computer vision-2023.pdf
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Lecture_3.pptx
Lecture_3.pptxLecture_3.pptx
Lecture_3.pptx
 
K10947 Vikas ct
K10947 Vikas ctK10947 Vikas ct
K10947 Vikas ct
 
Exploratory data analysis using r
Exploratory data analysis using rExploratory data analysis using r
Exploratory data analysis using r
 
Powerpointpresentation.c
Powerpointpresentation.cPowerpointpresentation.c
Powerpointpresentation.c
 
Intro matlab and convolution islam
Intro matlab and convolution islamIntro matlab and convolution islam
Intro matlab and convolution islam
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
K10765 Matlab 3D Mesh Plots
K10765 Matlab 3D Mesh PlotsK10765 Matlab 3D Mesh Plots
K10765 Matlab 3D Mesh Plots
 

Mehr von Smee Kaem Chann

Robot khmer engineer
Robot khmer engineerRobot khmer engineer
Robot khmer engineerSmee Kaem Chann
 
12 plancher-Eurocode 2
12 plancher-Eurocode 212 plancher-Eurocode 2
12 plancher-Eurocode 2Smee Kaem Chann
 
Matlab_Prof Pouv Keangsé
Matlab_Prof Pouv KeangséMatlab_Prof Pouv Keangsé
Matlab_Prof Pouv KeangséSmee Kaem Chann
 
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem ChannTravaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem ChannSmee Kaem Chann
 
New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8 New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8 Smee Kaem Chann
 
Matlab Travaux Pratique
Matlab Travaux Pratique Matlab Travaux Pratique
Matlab Travaux Pratique Smee Kaem Chann
 
The technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquakeThe technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquakeSmee Kaem Chann
 
Devoir d'Ă©lectricite des bĂȘtiment
Devoir d'Ă©lectricite des bĂȘtimentDevoir d'Ă©lectricite des bĂȘtiment
Devoir d'Ă©lectricite des bĂȘtimentSmee Kaem Chann
 
Rapport topographie 2016-2017
Rapport topographie 2016-2017  Rapport topographie 2016-2017
Rapport topographie 2016-2017 Smee Kaem Chann
 
Case study: Probability and Statistic
Case study: Probability and StatisticCase study: Probability and Statistic
Case study: Probability and StatisticSmee Kaem Chann
 

Mehr von Smee Kaem Chann (20)

stress-and-strain
stress-and-strainstress-and-strain
stress-and-strain
 
Robot khmer engineer
Robot khmer engineerRobot khmer engineer
Robot khmer engineer
 
15 poteau-2
15 poteau-215 poteau-2
15 poteau-2
 
14 poteau-1
14 poteau-114 poteau-1
14 poteau-1
 
12 plancher-Eurocode 2
12 plancher-Eurocode 212 plancher-Eurocode 2
12 plancher-Eurocode 2
 
Matlab_Prof Pouv Keangsé
Matlab_Prof Pouv KeangséMatlab_Prof Pouv Keangsé
Matlab_Prof Pouv Keangsé
 
Vocabuary
VocabuaryVocabuary
Vocabuary
 
Journal de bord
Journal de bordJournal de bord
Journal de bord
 
8.4 roof leader
8.4 roof leader8.4 roof leader
8.4 roof leader
 
Rapport de stage
Rapport de stage Rapport de stage
Rapport de stage
 
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem ChannTravaux Pratique Matlab + Corrige_Smee Kaem Chann
Travaux Pratique Matlab + Corrige_Smee Kaem Chann
 
Td triphasé
Td triphaséTd triphasé
Td triphasé
 
Tp2 Matlab
Tp2 MatlabTp2 Matlab
Tp2 Matlab
 
Cover matlab
Cover matlabCover matlab
Cover matlab
 
New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8 New Interchange 3ed edition Vocabulary unit 8
New Interchange 3ed edition Vocabulary unit 8
 
Matlab Travaux Pratique
Matlab Travaux Pratique Matlab Travaux Pratique
Matlab Travaux Pratique
 
The technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquakeThe technologies of building resists the wind load and earthquake
The technologies of building resists the wind load and earthquake
 
Devoir d'Ă©lectricite des bĂȘtiment
Devoir d'Ă©lectricite des bĂȘtimentDevoir d'Ă©lectricite des bĂȘtiment
Devoir d'Ă©lectricite des bĂȘtiment
 
Rapport topographie 2016-2017
Rapport topographie 2016-2017  Rapport topographie 2016-2017
Rapport topographie 2016-2017
 
Case study: Probability and Statistic
Case study: Probability and StatisticCase study: Probability and Statistic
Case study: Probability and Statistic
 

KĂŒrzlich hochgeladen

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vĂĄzquez
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

KĂŒrzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Lecture 02 visualization and programming

  • 1. 6.094 Introduction to programming in MATLAB Danilo Ơćepanović IAP 2010 Lecture 2: Visualization and Programming
  • 2. Outline (1) Functions (2) Flow Control (3) Line Plots (4) Image/Surface Plots (5) Vectorization
  • 3. User-defined Functions ‱ Functions look exactly like scripts, but for ONE difference Functions must have a function declaration Help file Function declaration InputsOutputs Courtesy of The MathWorks, Inc. Used with permission.
  • 4. User-defined Functions ‱ Some comments about the function declaration ‱ No need for return: MATLAB 'returns' the variables whose names match those in the function declaration ‱ Variable scope: Any variables created within the function but not returned disappear after the function stops running function [x, y, z] = funName(in1, in2) Must have the reserved word: function Function name should match MATLAB file name If more than one output, must be in brackets Inputs must be specified
  • 5. Functions: overloading ‱ We're familiar with » zeros » size » length » sum ‱ Look at the help file for size by typing » help size ‱ The help file describes several ways to invoke the function D = SIZE(X) [M,N] = SIZE(X) [M1,M2,M3,...,MN] = SIZE(X) M = SIZE(X,DIM)
  • 6. Functions: overloading ‱ MATLAB functions are generally overloaded Can take a variable number of inputs Can return a variable number of outputs ‱ What would the following commands return: » a=zeros(2,4,8); %n-dimensional matrices are OK » D=size(a) » [m,n]=size(a) » [x,y,z]=size(a) » m2=size(a,2) ‱ You can overload your own functions by having variable input and output arguments (see varargin, nargin, varargout, nargout)
  • 7. Functions: Excercise ‱ Write a function with the following declaration: function plotSin(f1) ‱ In the function, plot a sin wave with frequency f1, on the range [0,2π]: ‱ To get good sampling, use 16 points per period. ( )1sin f x 0 1 2 3 4 5 6 7 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
  • 8. Outline (1) Functions (2) Flow Control (3) Line Plots (4) Image/Surface Plots (5) Vectorization
  • 9. Relational Operators ‱ MATLAB uses mostly standard relational operators equal == not equal ~= greater than > less than < greater or equal >= less or equal <= ‱ Logical operators elementwise short-circuit (scalars) And & && Or | || Not ~ Xor xor All true all Any true any ‱ Boolean values: zero is false, nonzero is true ‱ See help . for a detailed list of operators
  • 10. if/else/elseif ‱ Basic flow-control, common to all languages ‱ MATLAB syntax is somewhat unique IF if cond commands end ELSE if cond commands1 else commands2 end ELSEIF if cond1 commands1 elseif cond2 commands2 else commands3 end ‱ No need for parentheses: command blocks are between reserved words Conditional statement: evaluates to true or false
  • 11. for ‱ for loops: use for a known number of iterations ‱ MATLAB syntax: for n=1:100 commands end ‱ The loop variable Is defined as a vector Is a scalar within the command block Does not have to have consecutive values (but it's usually cleaner if they're consecutive) ‱ The command block Anything between the for line and the end Loop variable Command block
  • 12. while ‱ The while is like a more general for loop: Don't need to know number of iterations ‱ The command block will execute while the conditional expression is true ‱ Beware of infinite loops! WHILE while cond commands end
  • 13. Exercise: Conditionals ‱ Modify your plotSin(f1) function to take two inputs: plotSin(f1,f2) ‱ If the number of input arguments is 1, execute the plot command you wrote before. Otherwise, display the line 'Two inputs were given' ‱ Hint: the number of input arguments are in the built-in variable nargin
  • 14. Outline (1) Functions (2) Flow Control (3) Line Plots (4) Image/Surface Plots (5) Vectorization
  • 15. Plot Options ‱ Can change the line color, marker style, and line style by adding a string argument » plot(x,y,’k.-’); ‱ Can plot without connecting the dots by omitting line style argument » plot(x,y,’.’) ‱ Look at help plot for a full list of colors, markers, and linestyles color marker line-style
  • 16. Playing with the Plot to select lines and delete or change properties to zoom in/out to slide the plot around to see all plot tools at once Courtesy of The MathWorks, Inc. Used with permission.
  • 17. Line and Marker Options ‱ Everything on a line can be customized » plot(x,y,'--s','LineWidth',2,... 'Color', [1 0 0], ... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10) ‱ See doc line_props for a full list of properties that can be specified -4 -3 -2 -1 0 1 2 3 4 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 You can set colors by using a vector of [R G B] values or a predefined color character like 'g', 'k', etc.
  • 18. Cartesian Plots ‱ We have already seen the plot function » x=-pi:pi/100:pi; » y=cos(4*x).*sin(10*x).*exp(-abs(x)); » plot(x,y,'k-'); ‱ The same syntax applies for semilog and loglog plots » semilogx(x,y,'k'); » semilogy(y,'r.-'); » loglog(x,y); ‱ For example: » x=0:100; » semilogy(x,exp(x),'k.-'); 0 10 20 30 40 50 60 70 80 90 100 10 0 10 10 10 20 10 30 10 40 10 50
  • 19. -1 -0.5 0 0.5 1 -1 -0.5 0 0.5 1 -10 -5 0 5 10 3D Line Plots ‱ We can plot in 3 dimensions just as easily as in 2 » time=0:0.001:4*pi; » x=sin(time); » y=cos(time); » z=time; » plot3(x,y,z,'k','LineWidth',2); » zlabel('Time'); ‱ Use tools on figure to rotate it ‱ Can set limits on all 3 axes » xlim, ylim, zlim
  • 20. Axis Modes ‱ Built-in axis modes » axis square makes the current axis look like a box » axis tight fits axes to data » axis equal makes x and y scales the same » axis xy puts the origin in the bottom left corner (default for plots) » axis ij puts the origin in the top left corner (default for matrices/images)
  • 21. Multiple Plots in one Figure ‱ To have multiple axes in one figure » subplot(2,3,1) makes a figure with 2 rows and three columns of axes, and activates the first axis for plotting each axis can have labels, a legend, and a title » subplot(2,3,4:6) activating a range of axes fuses them into one ‱ To close existing figures » close([1 3]) closes figures 1 and 3 » close all closes all figures (useful in scripts/functions)
  • 22. Copy/Paste Figures ‱ Figures can be pasted into other apps (word, ppt, etc) ‱ Edit copy options figure copy template Change font sizes, line properties; presets for word and ppt ‱ Edit copy figure to copy figure ‱ Paste into document of interest Courtesy of The MathWorks, Inc. Used with permission.
  • 23. Saving Figures ‱ Figures can be saved in many formats. The common ones are: .fig preserves all information .bmp uncompressed image .eps high-quality scaleable format .pdf compressed image Courtesy of The MathWorks, Inc. Used with permission.
  • 24. Advanced Plotting: Exercise ‱ Modify the plot command in your plotSin function to use squares as markers and a dashed red line of thickness 2 as the line. Set the marker face color to be black (properties are LineWidth, MarkerFaceColor) ‱ If there are 2 inputs, open a new figure with 2 axes, one on top of the other (not side by side), and activate the top one (subplot) 0 1 2 3 4 5 6 7 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0.2 0.4 0.6 0.8 1 plotSin(6) plotSin(1,2)
  • 25. Outline (1) Functions (2) Flow Control (3) Line Plots (4) Image/Surface Plots (5) Vectorization
  • 26. Visualizing matrices ‱ Any matrix can be visualized as an image » mat=reshape(1:10000,100,100); » imagesc(mat); » colorbar ‱ imagesc automatically scales the values to span the entire colormap ‱ Can set limits for the color axis (analogous to xlim, ylim) » caxis([3000 7000])
  • 27. Colormaps ‱ You can change the colormap: » imagesc(mat) default map is jet » colormap(gray) » colormap(cool) » colormap(hot(256)) ‱ See help hot for a list ‱ Can define custom colormap » map=zeros(256,3); » map(:,2)=(0:255)/255; » colormap(map);
  • 28. Surface Plots ‱ It is more common to visualize surfaces in 3D ‱ Example: ‱ surf puts vertices at specified points in space x,y,z, and connects all the vertices to make a surface ‱ The vertices can be denoted by matrices X,Y,Z ‱ How can we make these matrices loop (DUMB) built-in function: meshgrid ( ) ( ) ( ) [ ] [ ] f x,y sin x cos y x , ; y ,π π π π = ∈ − ∈ − 2 4 6 8 10 12 14 16 18 20 2 4 6 8 10 12 14 16 18 20 -3 -2 -1 0 1 2 3 2 4 6 8 10 12 14 16 18 20 2 4 6 8 10 12 14 16 18 20 -3 -2 -1 0 1 2 3
  • 29. surf ‱ Make the x and y vectors » x=-pi:0.1:pi; » y=-pi:0.1:pi; ‱ Use meshgrid to make matrices (this is the same as loop) » [X,Y]=meshgrid(x,y); ‱ To get function values, evaluate the matrices » Z =sin(X).*cos(Y); ‱ Plot the surface » surf(X,Y,Z) » surf(x,y,Z);
  • 30. surf Options ‱ See help surf for more options ‱ There are three types of surface shading » shading faceted » shading flat » shading interp ‱ You can change colormaps » colormap(gray)
  • 31. contour ‱ You can make surfaces two-dimensional by using contour » contour(X,Y,Z,'LineWidth',2) takes same arguments as surf color indicates height can modify linestyle properties can set colormap » hold on » mesh(X,Y,Z)
  • 32. Exercise: 3-D Plots ‱ Modify plotSin to do the following: ‱ If two inputs are given, evaluate the following function: ‱ y should be just like x, but using f2. (use meshgrid to get the X and Y matrices) ‱ In the top axis of your subplot, display an image of the Z matrix. Display the colorbar and use a hot colormap. Set the axis to xy (imagesc, colormap, colorbar, axis) ‱ In the bottom axis of the subplot, plot the 3-D surface of Z (surf) ( ) ( )1 2sin sinZ f x f y= +
  • 33. Specialized Plotting Functions ‱ MATLAB has a lot of specialized plotting functions ‱ polar-to make polar plots » polar(0:0.01:2*pi,cos((0:0.01:2*pi)*2)) ‱ bar-to make bar graphs » bar(1:10,rand(1,10)); ‱ quiver-to add velocity vectors to a plot » [X,Y]=meshgrid(1:10,1:10); » quiver(X,Y,rand(10),rand(10)); ‱ stairs-plot piecewise constant functions » stairs(1:10,rand(1,10)); ‱ fill-draws and fills a polygon with specified vertices » fill([0 1 0.5],[0 0 1],'r'); ‱ see help on these functions for syntax ‱ doc specgraph – for a complete list
  • 34. Outline (1) Functions (2) Flow Control (3) Line Plots (4) Image/Surface Plots (5) Vectorization
  • 35. Revisiting find ‱ find is a very important function Returns indices of nonzero values Can simplify code and help avoid loops ‱ Basic syntax: index=find(cond) » x=rand(1,100); » inds = find(x>0.4 & x<0.6); ‱ inds will contain the indices at which x has values between 0.4 and 0.6. This is what happens: x>0.4 returns a vector with 1 where true and 0 where false x<0.6 returns a similar vector The & combines the two vectors using an and The find returns the indices of the 1's
  • 36. Example: Avoiding Loops ‱ Given x= sin(linspace(0,10*pi,100)), how many of the entries are positive? Using a loop and if/else count=0; for n=1:length(x) if x(n)>0 count=count+1; end end Being more clever count=length(find(x>0)); length(x) Loop time Find time 100 0.01 0 10,000 0.1 0 100,000 0.22 0 1,000,000 1.5 0.04 ‱ Avoid loops! ‱ Built-in functions will make it faster to write and execute
  • 37. Efficient Code ‱ Avoid loops This is referred to as vectorization ‱ Vectorized code is more efficient for MATLAB ‱ Use indexing and matrix operations to avoid loops ‱ For example, to sum up every two consecutive terms: » a=rand(1,100); » b=zeros(1,100); » for n=1:100 » if n==1 » b(n)=a(n); » else » b(n)=a(n-1)+a(n); » end » end Slow and complicated » a=rand(1,100); » b=[0 a(1:end-1)]+a; Efficient and clean. Can also do this using conv
  • 38. End of Lecture 2 (1) Functions (2) Flow Control (3) Line Plots (4) Image/Surface Plots (5) Vectorization Vectorization makes coding fun!
  • 39. MIT OpenCourseWare http://ocw.mit.edu 6.094 Introduction to MATLABÂź January (IAP) 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.