Вы находитесь на странице: 1из 28

Lab 5: Matlab Tutorial

Due Sunday, Dec 7 at midnight


For this final lab, you should work with a partner. You know how to do that at this point.
Only one partner turns in the lab, but both of your names must be on the lab.

Matlab Introduction
To use Matlab:
You have 2 options on how to use Matlab:
1. Go to a campus lab where it is already installed and setup. This includes the Pearson lab
and the lab in the basement of Smith Hall as well as Spencer Lab. This is the cheapest and
probably the easiest option.
2. Buy a student / academic version of Matlab to install on your own computer. The basic
setup costs $99 and is good for your entire undergraduate years.
http://www.mathworks.com/academia/student_version/faq/prodinfo.html for information.

Matlab Info:
For more detail on how matlab works, you can look at
www.mathworks.com/help/techdoc/learn_matlab/bqr_2pl.html
Specifically, you might want to look at:

1-7 to 1-9, Starting and Quitting the MATLAB Program


2-2 to 2-20, Matrices and Arrays
3-56 to 3-70, Plotting
4-2 to 4-5, Programming -- Flow Control
4-20 to 4-23, Programming -- Scripts and Functions

The linked PDF is also available in web form at


www.mathworks.com/help/techdoc/learn_matlab/bqr_2pl.html

Instructions
Step 1: Start up both MATLAB and a web browser (Firefox)
Step 2: Type some expressions into MATLAB and see their effect
The following exercises are designed to get you comfortable with the MATLAB environment.
For now, we'll do all our work in the Command Window part of the MATLAB environment.
Try
>> 2^4
The python equivalent is 2**4. You should get the following result:
ans = 16
Try
>> area = pi * 4^2
Python has pi built into is math library. In Matlab you dont need to include the math library
to use pi. Try
>> x = sin(pi/2)

Again, Python has both sin and log built into a math library, whereas Matlab automatically
includes these. Try
>> y = log(2)
Take a minute and play with the command window.
Step 3: Write a MATLAB function into a file (a so-called "M-file" file)
As in python, you can work in a separate editor window and save your python code in a file,
ending with a .m for matlab:

myLab1.m

calculateAnswer.m

etc...

To create a new .m file, choose "File->New->Blank M-file". This will open an Editor
window where you can begin to type commands. Be patientit may take several seconds for
the new window to open!
Big Note Here: Matlab is annoying in that all functions must go in their own file.
Unlike Python, in which we are able to place multiple functions in the same file,
Matlab doesnt like that. Each function goes in its own separate file, named with
the functions name. The idea is that every function should be usable by all other
functions.
Comments:
Comments in Matlab are signified by putting % at the beginning of the line (as opposed to
python, which uses #). The header comments in your file should follow the commenting
style we used in class.
Example:
%
%
%
%
%

Description: calculates the area of a circle given the radius by


multiplying the radius squared and pi
Input: a number (for the radius)
output: a number (representing the area of a circle)
Examples: circleArea(5) = 78.5

function outputValue = circleArea(radius)


outputValue = pi * radius^2
The equivalent in Python is:
#
#
#
#
#

Description: calculates the area of a circle given the radius by


multiplying the radius squared and pi
Input: a number (for the radius)
output: a number (representing the area of a circle)
Examples: circleArea(5) = 78.5

def circleArea(radius):
return( pi * radius**2)
The big difference between how python defines functions and matlab defines functions
(other than calling it function verus def) is how matlab returns values. What matlab does is

creates something that is going to hold what is returned from the function. Right in the very
top line of the function definition, it tells you what is going to hold the value returned from
the function: we say outputValue = circleArea(radius). That means that the value in
outputValue is the value being returned from the matlab function circleArea. Then inside the
function, we give outputValue a value (a number, a string, a Boolean, a list, or some other
value) and that is what is returned from the function.
Note: DO NOT copy and paste this text. Type it into the MATLAB editor. MS Word
places special characters into its text that mess with MATLABs brain.
When you are finished, use the Save As command from the File menu to save the file with
the name circleArea.m
Step 4: Test your function in the command window
In the command window (the shell, not the matlab file circleArea.m), type in the following:
>>circleArea(5)
Note: You should get 78.5398 as the output. If you didnt, check your code.
Step 5: Create a new file named volume.m. Inside volume.m, write a matlab function that
takes 3 input parameters, the width, the height, and the depth. The function should return
the volume of the rectangle. Make sure the function is commented appropriately. Save the
file, then test it by running volume(3,7,2) (and other tests) in the shell.
Save this to turn in later
Step 6: Summing using loops:
Matlab has loops, just like python. It has both while loops and for loops (and can do
recursion as well). The while loops are quite similar to what youve seen in python.
However, the for loops use a bit of a different syntax (although they accomplish pretty much
the same thing.)
An example of a for loop (in a function) would be:
%
%
%
%
%
%
%
%

Description: This function calculates the sum of a series


of integers from 1 to finish and returns that sum.
Input: last integer in series of ints to be summed
Output: sum of integers from 1 to finish
Examples:
sumInts(5) -> 15
sumInts(10) -> 55
sumInts(12) -> 78

function total = sumInts(finish)


total = 0
for x = 1:finish
total = total + x
end
In this case, the for loop starts by initializing the variable x to hold 1. x will then be set to
hold every value up until the value finish . So if the value in the variable finish was 4, current
would first hold 1, then 2, 3, and finally 4. It stops when it is equal to the value inside of
finish. In other words, unlike Python, in matlab for loops the value starts at the
first value and continues THROUGH the last value.
We signify the end of the loop with the word end.

for loops are flexible. If nothing is specified, the variable automatically increases by 1 each
time through the loop. However, you can change the amount we increase the loop by. For
instance,
function printbyfives(endnum)
for count = 1:5:endnum
disp (count)
end
This should count by fives. (Note that the increment value is in the center, unlike python,
for which youd say,
for count in range(1,endnum+1,5):
In the above function, disp is used instead of print. Disp will print out whatever is between
the parentheses.
One other useful tidbit of information: you can use the mod function to get the remainder.
So, for instance,
>>mod(13,5)
ans = 3
>>mod(13,2)
ans = 1
mod(13,2) is the same as 13%2 in python.
Step 7: Open a new file in matlab, and save it as sumOddInts.py. Then, inside this file, write
the functions sumOddInts.
sumOddInts will use a for loop to sum all the odd integers between two parameters called
start and finish and return that value, e.g. sumOddInts(5,9) returns 21
Save this. Test it by running it from the shell.

Matlab Part 2: 2-Dimensional


Plotting:

Introduction to 2-D Plotting:

Tick-mark

Legend

Plotting Introduction:
The basic 2-D plotEXAMPLE
command is: plot
(x,y)
x is a vector (an array, or a list), and y is a
OF
A where
2-D PLOT
vector (an array, or list). Both vectors must have the same number of elements.

The plot command creates a single curve with the x values on the abscissa
(horizontal axis) and the y values on the ordinate (vertical axis).
TheData
curvesymbol
is made from segments of lines that connect the points that are
defined by the x and y coordinates of the elements in the two vectors.

Try it: Create two arrays (vectors) of numbers (note the lack of commas between elements
in your array, which is different from python):
>> x=[1 2 3 5 7 7.5 8 10];
>> y=[2 6.5 7 7 5.5 4 6 8];
Note: you dont need the commas in lists (vectors) in Matlab.
Then plot the two vectors:
>> plot(x,y)
Well, that was exciting. Now youve got a line plotted. I think we need to add a few things
though to make it more interesting. We can start with line specifiers. Line specifiers specify
information about how the line will appear. So, for instance: plot(x, y, - r +) will plot the
above line with a solid line (-), the line will be red (r) and the markers on the line will be +
(+). Below is a partial chart of possible line specifiers (awfully similar to pythons).
Line Style

Specifier

Solid
Dotted
Dashed
Dash-dot

:
--.

Line Color

Specifier

Red
Green
Blue
Cyan
Magenta
Yellow
Black
white

r
g
b
c
m
y
k
w

Marker
Type
Plus sign
Circle
Asterisk
Point
Square
diamond

Specifier
+
o
*
.
s
d

Try the following (and feel free to try any other combination youd like:
>> plot(x,y)

Tick-mark label

>> plot(x,y,r)
>> plot(x,y,--y)
>> plot(x,y,*)
>> plot(x,y,g:d)
Okay, thats a nice start. But what if we have something like this that we want to plot:
Year

1988

1989

Sales (M)

127

130

First, lets create our x coordinate:

1990
136

1991

1992

1993

145

158

178

1994
211

>>year = [1988:1:1994]
This creates an array with the first value being 1988, and including as a separate entry in
our array every value between 1988 and 1994 in increments of 1. In other words, our new
array called year will hold [1988 1989 1990 1991 1992 1993 1994] Type >>year at the
prompt to confirm.
Then create our y-coordinate:
>> sales=[127,130,136,145,158,178,211]
Now lets plot it:
>>plot(year,sales,- - r*)
You can also set the minimum and maximum limits for the x and y axis using axis([xmin
xmax ymin ymax]):
>>axis([1988 1994 120 220])
Okay, so far so good. However, this clearly represents the house sales in one neighborhood.
What if we wanted more than one line on our plot? Lets say we had a chart that looked
something like this:
Year
Sales(B)

1988
137

1989
130

1990
172

1991
204

1992
178

1993
158

1994
141

We can do this two ways: One is kind of moot at this point considering weve already
created our plot, but in the future if we know we want to plot more than one line
simultaneously, we can do it using:
plot(x,y,u,v,t,h)
This plots 3 graphs simultaneously: y versus x, v versus u, and h versus t. By default,
MATLAB makes the curves in different colors. The curves can have a specific style by adding
specifiers after each pair, for example:
plot(x,y,-b,u,v,r,t,h,g:)
In our case, however, weve already created our plot. We dont want to start over. Instead,
we can add another line to our plot using the hold on/hold of commands. What hold on
does is hold the current plot and all axis properties so that subsequent plot commands add
to the existing plot. Hold of returns to the default mode whereby plot commands erase the
previous plots and reset all axis properties before drawing new plots.
So lets try this method. Notice that in this case, the y array is the same as it was previously
for the first line on the graph. So we dont need to create a new array for the years.
However, we do need to create a new array for the new sales amounts. Lets do that first:
>> sales2 = [137,130,172,204,178,158,141]
Now lets place the new plot line on our existing plot:
>>hold on
>>plot(year,sales2,: cs)
>>hold off
Cool! We added another line to our plot!

Okay, our plot is looking pretty colorful. But what now? We probably want to save this, and
maybe we want to save it in a way we can use it in, say, a MS Word document. We can do
this using the print option: print <options> <filename>
Print options include:

-dtiff prints current figure to .tiff format (into filename.tiff)

-deps eps file

-depsc color eps file

-djpeg jpeg image

-dpng png image

So, for instance, if we wanted to save the current plot as a png image, wed do: print dpng
Ourplot.png.
Well save ours as a jpeg file.
>> print djpeg Houseplot.jpg
Now open up Houseplot.jpg (outside of Matlab) to make sure it looks like your Matlab plot.
Save this to turn in later.

Plotting equations:
Well plot the equation, y=3x3 26x + 10 and its first and second derivatives, for -2 <=x
<=4, all in the same plot.
First well make the vector x, holding the domain of the equation:
>>x=[-2:0.01:4]
(x now holds a vector from -2 to 4 by increments of .01)
Then well make the vector y with the equation value at each x value (Note: the .^ means to
the power of)
>>y=3*x^3-26*x+6
(3 multiplied by x to the 3rd power, minus 26 multiplied by x, plus 6)
(Note, when you multiply by x, youre creating an array in which you multiply by each value
in the x array. So really what were saying above is:
y[0] = 3*x[0].^3 26*x[0] + 6,
y[1] = 3*x[1].^3 26*x[1] + 6,
y[2] = 3*x[2].^3 26*x[2] + 6,

for each value in x)


Now well create a vector yd with the values of the first derivative:
>>yd = 9*x.^2-26
(9 multiplied by x squared, minus 26)
Now well create a vector ydd with the values of the second derivative:

>>ydd = 18*x
(In case you couldnt figure this one out, its just 18 multiplied by each x value)
And now well plot 3 lines, the function, the first derivative, and the second derivative:
>>plot(x,y,-b,x,yd,r,x,ydd,:k)
You should have a plot with a blue, a red, and a black line. Add a title, a legend, and an x
and y label. Then save this to a jpg file as derivativeplot.jpg.
Save this to turn in later.

Part 3: Plotting a function


What if you wanted to plot a function? You can! Matlab wouldnt be matlab if it didnt let
you plot a function! Say we wanted to plot:
y = 3.5-0.5xcos(6x) for -2<=x<=4
First wed create a vector, running from -2 to 4, with spacing of 0.01:
>>x = [-2:0.01:4]
Then we calculate a value of y for each value in x:
>>y=3.5.^(-0.5*x).*cos(6*x)
And then wed plot it (adding the line specifiers of your choice):
>>plot(x,y)
Add a title, a legend, and an x and y label. Then save this to a jpg file as plottingcos.jpg.
Save this to turn in.

A simple line plot (with labels)


Here are the MATLAB commands to create a simple plot of y = sin(3*pi*x) from 0 to 2*pi.
>> x = 0:pi/30:2*pi;
x is a vector (list) holding values from 0 to (and including) 2*pi, in increments of pi/30
>> y = sin(3*x);
y is a vector (list) holding the sin of 3* each value in x
>> plot(x,y)
>> xlabel('x (radians)');
label the x-axis
>> ylabel('sine function');
label the y-axis
>> title('sin(3*x)');
put a title on the plot
The effect of the labeling commands, xlabel, ylabel, and title are indicated by the text and
red arrows in the figure.

To turn in: Save the file using the File-> Save As->plot1.jpg (make sure you scroll down to
jpeg under save as file type) (if theres no jpg, ask the TA his preference for format)

A simple symbol plot


This example shows you how to plot data with symbols. This type of plot is appropriate, for
example, when connecting data points with straight lines would give the misleading
impression that the function being plotted is continuous between the sampled data points.
Here are the MATLAB commands to create a symbol plot with the data generated by adding
noise to a known function.
>> x = 0:0.01:2;
x holds a vector (a list) from 0 to 2 by increments of 0.01
>> noise = 0.02*randn(size(x));
this returns a list of random numbers that is the same length as x (each number is multiplied
by .02) this is a noise vector (list)
>> y = 5*x.*exp(-3*x) + noise;
y now holds a list of numbers, the exponent of x, with noise added to each number. So, for
each value of x, we take the exp(-3*x) * 5, and then add the noise value from the noise list.
>> plot(x,y,'o');
>> xlabel('x (arbitrary units)');
add axis labels and plot title
>> ylabel('y (arbitrary units)');
>> title('Plot of y = 5*x*exp(-3*x) + noise');
Note that the ''.*'' operator is necessary when multiplying the vector x by the vector exp(3*x). You should get the following plot:

To turn in: Save the file using the File-> Save As->plot2.jpg

An example of putting multiple curves on a plot


You saw this a bit in the previous lab, but heres the MATLAB commands for creating a
symbol plot with the data generated by adding noise to a known function. The original
function is drawn with a solid line and the function plus noise is plotted with open circles.
>> x = 0:0.01:2;
>> y = 5*x.*exp(-3*x);
>> yn = y + 0.02*randn(size(x));
yn now holds a noisy version of y
>> plot(x,y,'-',x,yn,'ro');
This plots both y and yn against x, so you can see the original function and the noisy
function. Notice that we put both x and y, followed by the symbol we want to use for that
line, and then x and yn and the color (red) followed by the symbol (o) we want to use for
that plot. See the next page for the resulting plot.
>> xlabel('x (arbitrary units)');
add axis labels and plot title
>> ylabel('y (arbitrary units)');
>> title('Plot of y = 5*x*exp(-3*x) + noise');
>> legend('true y','noisy y');
This adds the legend (in the top right corner, below). The first line plotted (the yellow,
smooth line) gets the label true y, and the second line plotted (the red line represented by
the o symbol) gets the label noisy y.
Note that the ''.*'' operator is necessary when multiplying the vector x by the vector exp(3*x).

To turn in: Save the file using the File-> Save As->plot3.jpg

Peaks
The peaks function is a function of two variables which produces example data that are
useful for demonstrating certain graphing functions (The data are created by scaling and
translating Gaussian distributions.) Calling peaks with a single argument n will create an
nxn matrix. We can use the peaks function to demonstrate the power of using a matrix
argument in the plot function. Try:
>>plot(peaks(100)
>>title(Plot of Peaks Function)
>>text(80,8.5,Peak value)
>>text(22,-7,Lowest peak value)
This adds text inside the plot at x = 80, y = 8.5. It then adds text at x=22, and y = -7.
(Cmon, isnt that cool?) What this plot plotted was a 100x100 matrix. So there are 100
separate lines on the graph. Now, if you have a matrix (in python this is, essentially, a list of
lists), you can plot it by inputting the matrix. (In python, what youre seeing is each list
plotted separately simply by entering the list of lists into the plot command).
To turn in: Save the file using the File-> Save As->plot4.jpg

Subplots
The subplot command allows you to subdivide the graphing window (the figure window) into
a grid of m rows and n columns, and place a separate plot into each of the squares in the
grid .
>> h = 1/16;
>> x = 0:h:1;
>> y = 0*x;
Makes a list of 0s the same length as x
>> y(1) = 1;
>> for i=2:max(size(y)),
y(i) = y(i-1) + h/y(i-1);
end
Note that indents dont matter in matlab. Its the word end that tells matlab where the for
loop ends. Weirdness that must be mentioned: i=2:max(size(y)) This gives us the length
of y, so were going from 2 up through the length of y. I couldve used length(y) here. I
COULD NOTve used size(y). Because in matlab everything is a matrix, so a list, or vector, or
array, is a 1 by x matrix. So if I type in size(y), I should get 1 17 (or however elements are

in y). By using max(size(y)), Im saying max (1,17), or 17. I was making your life
interesting.
>> true = sqrt(2*x+1)
Sets the vector true to hold the square root (function built into matlab) of 2* the value in x +
1
>> plot(x,y,'go',x,true)
look at your figure window
>> plot(x,abs(true-y),'mx')
Okay, so weve plotted them. But we want them to be plotted side by side so we compare
them:
>> subplot(1,2,1);
Im saying create a subplot grid of 1 by 2, and plot in the first square in the grid.
>> plot(x,y,'go',x,true)
>> subplot(1,2,2);
Im saying in the plot grid of 1 by 2, and plot in the second square in the grid.
>> plot(x,abs(true-y),'mx')
>> title ('Errors for h=1/32')
Adding a title, xlabel, and ylabel for the second plot
>> xlabel('x');
>> ylabel('|Error|');
>> subplot(1,2,1);
Switching back to the first plot to add labels
>> xlabel('x');
>> ylabel('|Error|')
>> title('Errors for h=1/16')
The figure you should get is:

To turn in: Save the file using the File-> Save As->plot5.jpg

Polar Plots:
Matlab provides plotting capabilities with polor coordinates. polar(theta, r) generates a polar
lot of angle theta (in radians) and a radial distance r.

Try:
>> theta = 0:0.2:5*pi
>> rho = theta.^2;
>> polar(theta, rho, '*')
>> subplot(1,1,1)
This sets the figure window back to being a 1x1 grid, with you plotting in the first square in
the grid.
>> polar(theta, rho, '*')
Your plot should look like this:

To turn in: Save the file using the File-> Save As->plot6.jpg

Bar Graphs and Pie Charts


Bar graphs, histograms, and pie charts are popular for reporting data. Here is a table of
some of the commonly used Matlab functions for creating bar graphs and pie charts:
bar(x)
barh(x)
bar3(x)
bar3h(x)
pie(x)
pie3(x)
hist(x)

When x is a vector (list), bar generates a vertical bar graph. When x is a 2dimensional matrix, bar groups the data by row
When x is a vector (list), bar generates a horizontal bar graph. When x is a 2dimensional matrix, bar groups the data by row
Generates a 3-dimensional bar chart
Generates a 3-dimensional horizontal bar chart
Generates a pie chart. Each element in the matrix is represented as a slice of
the pie.
Generates a 3-dimensional pie chart. Each element in the matrix is
represented as a slice of the pie.
Generates a histogram.

Lets try creating some of these plot types. Well be using the subplot function to put them
all in one figure window:
>> x = [1,2,5,4,8];
>> y = [x;1:5]
This creates a matrix (list of lists) of the x list and a list with values from 1 through 5.

>> subplot(2,2,1)
>> bar(x),title('A bar graph of vector x')
>> subplot(2,2,2)
>> bar(y),title('A bar graph of matrix y')
>> subplot(2,2,3)
>> bar3(y),title('A 3-dimensional bar graph')
>> subplot(2,2,4)
>> pie(x),title('A pie chart of x')
This stuff is just too cool! Heres what your results should look like:

To turn in: Save the file using the File-> Save As->plot7.jpg
A histogram is a special type of graph that is particularly useful for the statistical analysis of
data. A histogram is a plot showing the distribution of a set of values. In Matlab, the
histogram computes the number of values falling into 10 bins (categories) that are equally
spaced between the minimum and the maximum values. For example, if we define a matrix
x as the set of grades from the Introduction to Computer Science final, the scores could be
represented in a histogram, as shown below, and generated using the following code:
>> subplot(1,1,1)
>> x = [99,77,88,66,72,51,95,78,71,69,47,82,91,73,76,83,75,93,82,31];
>>hist(x)
This will give you a histogram with 10 bins. If you want a finer grade, youd enter the
number of bins you want. For example:
>>hist(x,25)
will create a histogram with 25 bins. The figure will look like this:

To turn in: Save the file using the File-> Save As->plot8.jpg
Note: if you ever want help with plotting, you can just type
>>help plot
into the command window in matlab and youll get helpful information on plotting.

Part 3: Matlab Plotting: 3-D


Plotting
Matlab offers some neat 3-dimensional plotting functions such as plot3, mesh, surf, etc.
Well start with a basic 3-D line plot. This is essentially the same as the 2-D line plot, only
youll need a 3rd vector (array). Try the following:
>> z = 1:0.01:1000;
>> x = sin(z);
>> y = cos(z);
>> plot3(x,y,z)
You should get something like this:

You can use plot3 to plot any 3 vectors in this way. You can add titles, labels, etc. in the
same way that you added them to the 2-D plot. You can label the z axis using the labeling
zlabel.
Sidenote: if you want to create a vector of x equally spaced numbers between y and z, you
can use the linspace function. The default is to create 100 numbers. So, for instance, to
create a vector of 100 evenly spaced numbers between 0 and 200, youd use the following
command:
>>v = linspace(0,200)
This would give you a vector similar to:
>>v = 0:2:200
The difference here is you get to specify the number of points you want in the vector. To
override the default, youd use the 3rd parameter:
>>v = linspace(0,210,30)
This will give you 30 equally spaced points between 0 and 210.
You can use linspace if you know the number of points you want, but not necessarily the
increment value.
To turn in: a 3-d plot using plot3, saved as a .jpg file (ThreeD.jpg)
If you want to see the animated version of the plot, try:
>>>comet3(x,y,z)
with the figure window open and watch the plot happen (its slow!)
Mesh and Surface Plot:
These plots allow you to plot the data as a surface.
You can use the mesh plot to plot a 2-dimensional matrix. If you do this, the x and y values
are the dimensions of the matrix, and the z value is the value at x,y in the matrix. So, for
example, if I made the following matrix:
>> z = [1:10;2:2:20;3:12]
I just created a matrix with 3 rows (separated by ;) and 10 columns, 1-10 in the first row, 220 by 2s in the second row, and 3-12 in the third row. Now if I do:
>>mesh(z)
the x axis is 3, the y axis is 10, and z is the value at each point, or the surface being plotted.
The resulting plot will look like this:

The graph is created by connecting the points defined in z ( the matrix) into a rectilinear
grid. Notice that x goes from 1 3 (the number of rows) and y goes from 1 10 (the number
of columns in the matrix).
To turn in: a mesh plot using mesh, saved as a .jpg file (Mesh.jpg)
Surface Plots:
Surface plots are mesh plots colored in. You can do a surface plot of the mesh plot you just
did to see the difference:
>>surf(z)
Again, the x and y coordinates are the number of rows and columns, respectively, and the z
values in the matrix are those plotted as the surface plot. You should get something like
this:

You can control the shading of the surface plot using the shading command. What youre
seeing above is the default shading, a.k.a. faceted flat. Its not very interesting. You can get
cooler surface maps using shading interp. Try the following:
>>z=peaks(25);
>>surfl(z);
You should get something like this:

Then try:
>>shading interp;
>>colormap(colorcube);
You should get something like:

Oh, cmon. Thats really cool. I have no idea when youd need to use the colorcube for
shading of a surface map, but it looks really neat. Other colormap options are:
autumn
bone
hot
spring
colorcube
hsv
summer
cool
pink
winter
copper
prism
jet(default)
flag
white
To turn in: a surface plot with interpolated shading, using the colormap of your
choice, saved as a .jpg (Interp.jpg)

Contour Plot
You can also make a plot, which is a 2-dimensional representation of a 3-dimensional
surface. It takes a matrix, and then chooses the number of contour levels automatically
based on the values in the matrix. So if we take the surface map from the previous example
and flatten it, then plot it, that would be a contour plot. To do it, do the following (in this
example, were overriding the default number of contour levels and specifying that we want
16 different contour levels):
>>z=peaks(25);
>>contour(z,16);
>>colormap(hsv)
You should get something that looks like this:

To turn in: a contour plot using the colormap of your choice, saved as a .jpg file
(Contour.jpg)
Pseudo ColorPlots
If youd prefer to have a contour plot that is shaded, instead of with distinct edges, youd
use a pseudo color plot. Again, this plot takes as input a matrix. So lets try it:
>> z = peaks(25);
>>pcolor(z);
>>shading interp;
You should get something like this:

To turn in: a pseudocolor plot, saved as a .jpg file (ColorPlot.jpg)


Quiver or Velocity Plots
A quiver plot displays velocity vectors as arrows with components (u,v) at the points (x,y).
For example, the first vector is defined by components u(1),v(1) and is displayed at the point
x(1),y(1).
So, a simple example would be:
>> x = [1 12];
>> y = [1 2];
>> u = [3 4];
>> v = [4 6];
>> quiver(x,y,u,v);
You should get a plot that looks like this:

Here we see that the first vector is represented as an arrow, starting at coordinates 1, 1, and
then travels in the direction of over 3 and up 4. The second vector starts at coordinates 12,
2 and travels in the direction of over 4 and up 6.
For quiver to work, the matrices x, y, u, and v must all be the same size and contain
corresponding position and velocity components. By default, the arrows are scaled to just
not overlap, but you can scale them to be longer or shorter if you want.
quiver(...,scale) automatically scales the arrows to fit within the grid and then stretches
them by the factor scale. scale = 2 doubles their relative length, and scale = 0.5 halves the
length. Use scale = 0 to plot the velocity vectors without automatic scaling.
Try the following (from Mathworks):
>>x = -2:.2:2;
>>y = -1:.2:1;
>>[xx,yy] = meshgrid(x,y);
>>zz = xx.*exp(-xx.^2-yy.^2);
>>[px,py] = gradient(zz,.2,.2);
>>quiver(x,y,px,py,2);

You should get a plot that looks like this:

To turn in: a quiver plot, saved as a .jpg file (Quiver.jpg)

Slice plotting:

slice displays orthogonal slice planes through volumetric data.


slice(V,sx,sy,sz) draws slices along the x, y, z directions in the volume V at the points in the
vectors sx, sy, and sz. V is an m-by-n-by-p volume array containing data values at the
default location X = 1:n, Y = 1:m, Z = 1:p. Each element in the vectors sx, sy, and sz defines
a slice plane in the x-, y-, or z-axis direction. (Mathworks).
In the following command:
slice(X,Y,Z,V,sx,sy,sz)
X, Y, and Z are 3 dimensional arrays specifying the coordinates for V
X, Y, and Z must be monotonic and orthogonally spaced (this is what meshgrid produces for
us).
So try the following:
>>[x,y,z] = meshgrid(-2:.2:2,-2:.25:2,-2:.16:2);
>>v = x.*exp(-x.^2-y.^2-z.^2);
>>xslice = [-1.2,.8,2];
>>yslice = 2;
>>zslice = [-2,0];
>>slice(x,y,z,v,xslice,yslice,zslice)
>>colormap colorcube
You should get something like this:

To turn in: a slice plot, saved as a .jpg file (Slice.jpg)


(Note: You can do all of this in python as well using the matplotlib and possibly scipy and
numpy libraries)
End of 3-D Plotting

Matlab Part 4:
Turn on the diary function.
>> diary matlablab5.txt
Leave the diary file on while you complete the following exercises: (Note if you mess up,
you dont have to start over from the beginning. After youve finished, you can go back and

edit out the stuff you dont want. Technically you could also just type in both all the
questions and the answers, but if you want to get it done in one lab, you should probably let
Matlab calculate the results for you.

Matlab does Linear Algebra:


This lab will introduce you to some basic linear Algebra functions available to you in Matlab.
Matlab allows for very easy computations with vectors and matrices.

Basic Vector Manipulation:


Start by creating the following matrices:
>>a=[123]
a=
123
>>b=[1;2;3]
b=
1
2
3
Command length returns the number of components of a vector
>>length(a)
ans=
3
The dot operator. plays a specific role in MATLAB. It is used for the component-wise
application of the operator that follows the dot operator. In this example, a.*a goes through
the vector a systematically and multiplies the first value in a by the first value in a, the
second by the second, etc. Try it:
>>a.*a
ans=
149
The same result is obtained by applying the power operator ^ to the vector a
>>a.^2
ans=
149
For the purpose of the next example let us change vector a to the column vector
>>a=a'
a=
1
2
3
The dot product of vectors a and b is calculated as follows:
a = 1 2 3
a*b is: 1*1 + 2*2 + 3*3. Try it:
>>dotprod=a'*b
dotprod=

14
The outer product of vectors a and b are calculated as follows:
1
2
3
*
123
=
1 2
3
2 2*2 2*3
3 3*2 3*3
>>outprod=a*b'
outprod=
123
246
369
The cross product of two three-dimensional vectors creates a third vector perpendicular to
the first two. It is calculated using command cross. Let the vector a be the same as above
and make b be:
>>b=[212];
Note that the semicolon after a command avoids display of the result. The cross product of a
and b is
>>cp=cross(a,b)
cp=
185
The cross product vector cp is perpendicular to both a and b, so
>>[cp*acp*b']
ans=
00
Matrices:
We will now deal with operations on matrices.
Create a 3-by-3 matrix:
>>A=[123;456;7810]
A=
123
456
7810
To extract a submatrix B consisting of rows 1 and 3 and columns 1 and 2 of the matrix A do
the following
>>B=A([13],[12])
B=
12
78

To interchange rows 1 and 3 of A use the vector of row indices together with the colon
operator:
>>C=A([321],:)
C=
7810
456
123
(Doesthismakesensetoyou?Ifnot,slowdownandfigureoutwhatisgoing
onhere.)
To delete a row (column) use the empty vector operator [ ]
>>A(:,2)=[]
A=
13
46
710
Second column of the matrix A is now deleted. (Doesthismakesensetoyou?Ifnot,
slowdownandfigureoutwhatisgoingonhere.)
To insert a row (column) we use the technique for creating matrices and vectors (Note that
were inserting column1 and column3 directly from A itself). The second column is inserted
as a vector':
>>A=[A(:,1)[258]'A(:,2)]
A=
123
456
7810
Matrix A is now restored to its original form.

Dot Operator on Matrices:


The dot operator . works for matrices too. Let now create a 2x3 matrix:
>>A=[123;321];
The following command:
>>A.*A
ans=
149
941
computes the entry-by-entry product of A with A. However, the following command
generates an error message:
>>A*A
???Errorusing==>*
Innermatrixdimensionsmustagree.
Why? Because A*A is attempting to do matrix multiplication. (Make sure you understand this!)

Matrix Inverse

MATLAB function inv is used to compute the inverse matrix.


Let the matrix A be defined as follows:
>>A=[123;456;7810]
A=
123
456
7810
Then
>>B=inv(A)
B=
0.66671.33331.0000
0.66673.66672.0000
1.00002.00001.0000
In order to verify that B is the inverse matrix of A it sufficies to show that A*B = I and B*A =
I, where I is the 3-by-3 identity matrix. We have
>>A*B
ans=
1.000000.0000
01.00000
001.0000
In a similar way one can check that B*A = I.

Matlab does Determinants


In some applications of linear algebra knowledge of the determinant of a matrix is required.
According to Wikipedia,
In algebra, the determinant is a special number associated with any square matrix. The
fundamental geometric meaning of a determinant is a scale factor for measure when the
matrix is regarded as a linear transformation. Thus a 2 2 matrix with determinant 2 when
applied to a set of points with finite area will transform those points into a set with twice the
area.
MATLAB built-in function det is designed for computing determinants.
Lets start with a magic square. A magic square is an n by n matrix constructed from the
integers 1 through n^2 with equal row and column sums. n must be greater than or equal
to 3. Try it:
>>A=magic(3)
You should get a 3x3 matrix. The following is an example of a possible matrix created using
magic:
M=

8
3
4

1
5
9

To check, try:
>>sum(M)
>>sum(M)
>>sum(diag(M))

6
7
2

Determinant of A is then determined using:


>>det(A)
ans=
360
>>diaryoff

Part 5:
If you are done, woo woo! Take a moment to pause to enjoy the feeling, then get working on
your final project.

To Turn In:

Matlab files:
CircleArea.py
Volume.py
SumOddInts.py

Plots(2-D)
1. Houseplot.jpg
2. derivativeplot.jpg
3. plottingcos.jpg
4. plot1.jpg
5. plot2.jpg
6. plot3.jpg
7. plot4.jpg
8. plot5.jpg
9. plot6.jpg
10. plot7.jpg
11. plot8.jpg
Plots(3-D)

ThreeD.jpg
Mesh.jpg
Interp.jpg
Contour.jpg
ColorPlot.jpg
Quiver.jpg
Slice.jpg

Part 4:

Your Matlablab5.txt file(be sure to include your name in the file)

Вам также может понравиться