MATLAB Lab 2
Visualization and Programming
Outline
(1) Plotting Continued
(2) Scripts
(3) Flow Control
Cartesian Plots 50
10
We have already seen the plot function
40
10
30
10
x=-pi:pi/100:pi;
y=cos(4*x).*sin(10*x).*exp(-abs(x));
20
10
plot(x,y,'k-'); 10
10
0
10
0 10 20 30 40 50 60 70 80 90 100
The same syntax applies for semilog and loglog plots
semilogx(x,y,'k');
semilogy(y,'r.-'); Use semilogx if you want logarithmic x-axis
loglog(x,y); Use semilogy if you want logarithmic y-axis
Use loglog if you want both axes logarithmic
Try this
>> x = 0:100;
>> semilogy(x, exp(x), ‘k.-’);
Playing with the Plot
to select lines
and delete or
change to see all plot
properties tools at once
to slide the plot
to zoom in/out around
Line and Marker Options
Everything on a line can be customized
plot(xi,yi,linespec,’property name’…
……,’property value’
0.8
0.6
0.4
See doc line for a full list of 0.2
properties that can be specified
0
-0.2
Try this -0.4
>> x = 0:pi/100:2*pi -0.6
>> y = sin(x)
>> plot (x,y, ‘k.-‘, ‘LineWidth’, 2, -0.8
-4 -3 -2 -1 0 1 2 3 4
‘MarkerEdgeColor’, ‘k’, ‘MakerFaceColor’,
‘g’, ‘MarkerSize’,10);
Labels
To add titles and labels using the command -line
title('Stress-Strain');
xlabel('Force (N)');
For multiple lines, add a legend entry for each line
legend('Steel','Aluminum','Tungsten');
Can specify font and size for the text Tip: Use … to break long
commands across
ylabel('Distance (m)','FontSize',14,...
multiple lines
'FontName','Helvetica'); like this
To put parameter values into labels, need to use num2str and concatenate:
str = [‘Strength of ' num2str(d) 'cm diameter rod'];
title(str)
Axis
A grid makes it easier to read values
grid on
xlim sets only the x axis limits
xlim([-pi pi]);
ylim sets only the y axis limits
ylim([-1 1]);
To specify both at once, use axis:
axis([-pi pi -1 1]);
sets the x axis limits between -pi and pi and the y axis limits between -1 and 1
Learn more on advanced figure customization from HELP
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)
axis ij
puts the origin in the top left corner (for viewing matrices)
Multiple Plots in one Figure
Use the figure command to open a new figure
figure
or activate an open figure
figure(1)
To have multiple axes in one figure
subplot(2,3,1) or subplot(231)
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)
Figures: Exercise
Open a figure and plot a sine wave over two periods with data
points at 0, pi/8, 2pi/8… . Use black squares as markers and a
dashed red line of thickness 2 as the line
Save the figure as a pdf
View with pdf viewer.
>> figure;
>> plot(0:pi/8:4*pi,sin(0:pi/4:4*pi),'rs--',...
'LineWidth',2,'MarkerFaceColor','k');
3D Line Plots
We can plot in 3 dimensions just as easily as in 2
Use the plot3 function
Try this:
>> time = 0:0.001:4*pi;
>> x = sin(time);
>> y = cos(time);
>> z = time;
>> plot3(x,y,z,’k’,’Linewidth’,2)
10
Use tools on figure to rotate it 5
Can set limits on all 3 axes 0
-5
xlim, ylim, zlim -10
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
Surface Plots
It is more common to visualize surfaces in 3D
f x, y sin x cos y
Example: x , ; y ,
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
surf
Make the x and y vectors
x=-pi:0.1:pi; meshgrid is equivalent to executing a
y=-pi:0.1:pi; nested loop (to scan through all values of x
and y) to plot a surface
The rows of the output array X are copies of
the vector x,
Use meshgrid to make matrices columns of the output array Y are copies of
the vector y
[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 Options
See help surf for more options
There are three types of surface shading
shading faceted
shading flat
shading interp
contour
You can make surfaces two-dimensional by using contour
contour(X,Y,Z,'LineWidth',2)
Try this:
takes same arguments as surf >> x = -pi:0.01:pi;
>> y = -pi:0.01:pi;
color indicates height >> [X,Y] = meshgrid(x,y);
can modify linestyle properties >> Z = cos(X).*sin(Y);
>> [C,h] = contour(X,Y,Z)
hold on >> clabel(C,h)
mesh(X,Y,Z) Each contour line is labelled
Exercise: 3-D Plots
Plot exp(-0.1(x^2+y^2))*sin(xy) for x,y in [–2*pi,2*pi]
with interpolated shading
>> x=-2*pi:0.1:2*pi;
>> y=-2*pi:0.1:2*pi;
>> [X,Y]= meshgrid(x,y);
>> Z =exp(-0.1*(X.^2+Y.^2)).*sin(X.*Y);
>> surf(X,Y,Z);
>> shading interp
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
8
6
4 8
2 6
4
0 2
-2 0
-4 -2
-4
-6 -6
-8 -8
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));
see help on these functions for syntax
doc specgraph – for a complete list
Outline
(1) Plotting Continued
(2) Scripts
(3) Flow Control
Scripts: Overview
Scripts are
written in the MATLAB editor
saved as m-files (.m extension)
evaluated line by line
To create an m-file from command-line
edit myScript.m
or click
Scripts: the Editor
* Means that it's not saved
Line numbers
m-file path
Debugging tools
Help file
Comments
Possible breakpoints
Scripts: Good Practice
Take advantage of "smart indent" option
Keep code clean
Use built-in functions
Vectorize, vectorize, vectorize
When making large matrices, allocate space first
Use nan or zeros to make a matrix of the desired size
Keep constants at the top of the m-file
COMMENT!
Anything following a % is seen as a comment
The first contiguous comment becomes the script's help file
Comment thoroughly to avoid wasting time later
Exercise: Scripts
A student has taken three exams. The performance on
the exams is random (uniform between 0 and 100)
The first exam is worth 20%, the second is worth 30%,
and the final is worth 50% of the grade
Calculate the student's overall score
Save script as practiceScript.m and run a few times
>> scores=rand(1,3)*100;
>> weights=[0.2 0.3 0.5];
>> overall=scores*weights’
Outline
(1) Plotting Continued
(2) Scripts
(3) Flow Control
Relational Operators
Matlab uses mostly standard relational operators
equal ==
not equal ~=
greater than >
less than <
greater or equal >=
less or equal <=
Logical operators normal bitwise
And & &&
Or | ||
Not ~
Xor xor
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 ELSE ELSEIF
if cond if cond if cond1
commands commands1 commands1
end else elseif cond2
commands2 commands2
end else
Conditional statement:
evaluates to true or false commands3
end
• No need for parentheses: command blocks are between
reserved words
for
for loops: use for a definite number of iterations
MATLAB syntax:
Loop variable
for n=1:100
commands
end Command block
The loop variable
Is defined as a vector
Is a scalar within the command block
Does not have to have consecutive values
The command block
Anything between the for line and the end
while
The while is like a more general for loop:
Don't need to know number of iterations
WHILE
while cond
commands
end
The command block will execute while the conditional
expression is true
Infinite Loop
while true
commands
end
Exercise: Control-Flow
Write a function to calculate the factorial of an integer N using a loop (you can use
a for or while loop). If the input is less than 0, return NaN.
Write a script that takes a number from the user and calculates the factorial of the
number using the function you made in the above step infinitely (Use the input
function. Go through its help)
Visualize the surface defined by the function f(x,y) = x . exp(-x^2 – y^2) in MATLAB.
x [-2, 2], y [-2,2]. Step size is 0.2 for both x and y.
function a = factorial(N)
if N<0,
a=nan,
else
a = 1;
for k=1:N
a = a*k;
end
end
[X,Y] = meshgrid(-2:.2:2, -2:.2:2);
2:.2:2);
Z = X .* exp(-X.^2 - Y.^2);
surf(X,Y,Z)