Matlab Lab 2: Visualization and Programming
Matlab Lab 2: Visualization and Programming
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
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
-0.2
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
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)
>> figure;
>> plot(0:pi/8:4*pi,sin(0:pi/4:4*pi),'rs--',...
'LineWidth',2,'MarkerFaceColor','k');
3D Line Plots
10
-5
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
Help file
Comments
Possible breakpoints
Scripts: Good Practice
Take advantage of "smart indent" option
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
>> 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
for n=1:100
commands
end Command block
WHILE
while cond
commands
end