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

Matlab Fundamentals

Tom Huber, Gustavus Adolphus College


Envision It Workshop, February 1, 1997
Matlab is a versatile program which allows you to use a computer to solve a vast number of
problems in science and mathematics both numerically and through visualization. Some of the
strengths of Matlab are:

Flexibility to solve a large number of problems


Good tools for visualization
Can be used on most computer systems (Mac, PC, Unix Workstation, Cray, ...)
Used at many colleges, universities and industry in many different disciplines (science,
math, computer science, finance)
The scripting language is relatively easy to learn, and is complementary with traditional
programming languages (BASIC, FORTRAN, C, Pascal)

The goal of this tutorial is to familiarize you with the fundamentals of Matlab (defining
variables, doing calculations and creating graphs). In our next session, we will use these
fundamentals to develop Matlab script files (programs) to solve more complicated models.

What can we use Matlab for?


1.
2.
3.
4.
5.
6.

Simple calculations
Plotting and analyzing mathematical relationships (2D and 3D)
List & Matrix Operations
Writing script files (a type of programming)
Symbolic manipulation of equations
Advanced visualization, animation and GUI interface tools

We will concentrate on Numbers 1-3 (with a brief discussion of Numbers 4 and 5) in this session
and Number 4 in our next session

For many of the calculations in this document, we will be using the ideal gas equation

P*V = n*R*T

P = Pressure in Atmospheres
V = Volume (in Liters)
n = Number of Moles of Gas
R = 0.0821 Atm*Liters/mol*Kelvin
T = Temperature in Kelvin

Matlab Basics
1. The command diary file_name command saves all subsequent output to file
file_name

2. Creating and using variables


o Type in P=1<ENTER> n=1<ENTER> R=0.0821<ENTER> T=273<ENTER>
o Variable names are case sensitive (so T is not the same is t). Variable names can
include letters or numbers
o Other legal variable names would be Pressure, Vol, nMoles, Rvalue, T1,
...

3. You can recall previous lines by using up-arrow key


4. Arithmetic Operations & Simple Calculations (+, -, *, /, ^)
o The volume can be determined by typing V= n*R*T/P
5. The role of the Semi-colon in Matlab
o Matlab will print out the answer for any command not terminated by a semicolon.
o Matlab will not print out the result if the line ends in a semi-colon
6. To find out help on a command (such as plot), type help plot (or use the pulldown
help menu)
7. To list all commands which have a keyword in their description (such as sin), type
lookfor sin

Lists & List Arithmetic


In addition to doing operations on single numbers, Matlab allows us to perform operations on a
list of numbers. These lists are also called Vectors, Arrays or Matrices in the Matlab manuals.
1. There are several ways to create a list
o Using the Colon notation, e.g. T= 300:10:400;
o Using the zeros and ones commands, e.g. y=zeros(1,3); z = ones(1,5);
o Explicitly listing terms, e.g. x = [1 4 9 16]
o Reminder: If you do not include a semi-colon, the entire list will be printed
2. We can do addition, subtraction, multiplication and division of a list and a value using the
(+, -, *, /) operators. Try, for example, T*2 , T/5, T+20, T/10+5
3. Array operations on a list (.* ./ and .^ operators) operate on each element of the list
individually
4. Try x=1:3 y=2:4 then type operations like x.*y, x./y, x.^y

5. Type in T=300; V = 10:20; P=n*R*T./V to get the pressure at several different


volumes
6. There are many intrinsic Functions (sin, cos, exp, ...) which can operate on list elements.
angle=0:pi/4:pi, sin(angle)

Creating Plots
1. To plot two lists, enter a command such as plot(V,P)
2. To select axis range use the axis command with a 4 element list containing [xmin,
xmax, ymin, ymax], e.g. axis([5 8 1 2])
3. To set colors and line types use optional plot arguments
o plot(V,P,'ro') or plot(V,P,'b--')
4. To overlay graphs, type hold on and subsequent graphs will be on the same axes. To
start a new graph, type hold off
5. Labels and titles can be added by using commands such as
o
o
o

6. To

xlabel('Volume (in Liters)')


ylabel('Pressure (in Atm)')
title('Ideal Gas Plot')
zoom in on a graph, type zoom on and highlight

a region with a mouse

For Further Information

There are additional handouts on the fundamentals of matrices, script files and symbolic
math. There are several problems which you can study in a separate document
There is an excellent tutorial in the Student Edition of Matlab manual
The book Mastering Matlab, by Duane Hanselman & Bruce Littlefield (Prentice Hall,
1996)
There are many well written tutorials on the WWW, including
o
o

http://www.indiana.edu/~statmath/smdoc/Matlab.html
http://www.geodyn.psu.edu/GEOSC203/tutorial.html
The Mathworks homepage for Matlab is http://www.mathworks.com
The Mathworks education homepage is http://education.mathworks.com
Other resources can be found at http://physics.gac.edu/~huber/matlab/

Electronic Copy: http://physics.gac.edu/~huber/matlab/mtlabfun.htm


Revised: 28-JAN-97 by Tom Huber, Physics Department, Gustavus Adolphus College.

Visualization of Diffusion Model Results


In the diffusion model we have developed, we had only one way of visualizing the results,
namely a series of plots of values versus time. Below we will use some of Matlab's powerful
features to enhance our ability to understand and visualize the results.
In particular, we are going to modify the previous program so it stores all the profiles in a
2 dimensional array where each column represents the values (for example, the volume
of water in each cell) at a subsequent time step. Then we will be able to use this result in
a number of ways:

Viewing it as a surface, we can see the trends in the flow.


We can slice it so we can see the values versus position at any time, or the values
versus time at any position.
We can take successive slices and view them as a "movie" to watch the flow

First, copy your program program diff1.m to diff1b.m. Modify the program diff1b.m
by doing the following:
1. Add a statement AllValues=Values; right before the first for loop. This will store
the initial distribution in the array AllValues
2. Remove all of the plotting statements from near the end of the program. In their
place, we will append the updated column of values onto the array of previous
values by including the statement AllValues=[AllValues Values]; (this is similar
to what we did in Steve McKelvey's tutorial on population growth)
Now when we run the program, it will create the array AllValues where successive
columns of the array have the values versus position.

Visualization Tutorial Tasks


1. Make a script file valsurf.m that will plot and label the surface
2.
3.
4.
5.
6.
7.
8.
9.

% VALSURF.M
Plot the surface from the diffusion model
clf;
% Clear the current figure
surf(AllValues)
% Plot the surface
colormap(jet)
% Change the colormap
view(0,90)
% Set the viewpoint to be above
colorbar
% Show a colorbar which has the values
xlabel('Time Step')
% Label the axes
ylabel('Position')

Experiment with other views of the same surface by typing in a command such
as view(150,30) (the first arguement is the rotation angle of the XY plane around
the Z axis, and the second arguement is the view angle above the XY plane.

10. We can extract a row or column from the AllValues matrix using, for example
Values=AllValues(10,:) to extract the 10th row or Values=AllValues(:,5) to
extract the 5th column. Plot the resulting Values and interpret the results.
11. Make an M-File plotloc.m which will ask the user for a cell number (hint: use the
input statement) and then will extract the values versus time for that location
from AllValues. Make a plot of this (including labels), and also print out (using
the disp command) the maximum value and time step when it occurs (to do
this, use the max statement. In particular, the command
[ValMax LocMax] = max(Values);

will store the maximum value of the array Values in the variable ValMax and the
location in the array (the element number) in LocMax

12. Use the program above to answer questions such as: When does the crest
(maximum) occur for a position 5 cells downstream from the initial
concentration? What about 15 cells downstream? Does doubling the initial
concentration double the crest at these locations?
13. Perform the command AllValues1=AllValues (so that the current array is stored
in this variable). Modify your program diff1b.m in some way (for example,
changing the fractions to left, right and same) and re-run the program. Now
modify your M-file plotloc.m from the previous task to extract and plot (on the
same graph) both the values from AllValues and AllValues1. This will allow you
to directly compare the results of two different models.
14. Make a script file valmovie.m which extracts successive columns from AllValues
and plots these one after another. This "movie" will be similar to the output from
our original program diff1.m (from the previous handout). You could even plot
both AllValues and AllValues1 on the same graph.
At this point, we have a method for running the model to produce an output file and
then to visualize the results using the programs valsurf, plotloc and valmovie. We can
now add additional details to our model to make it closer to the actual situation that
would exist in a river. You may want to work as a group on some of the following tasks
which extend the model.

Group Tutorial Tasks

1. We modeled our source as coming at one time from one location (this would be
a good model for a sudden pollution spill at some position). A more realistic
model for snow melting would be a reservoir which melts and puts this melting
snow into the river. Make a new version of your program which does the
following:
o Defines an initial reservoir of material
o During the iteration for each day (the for i=1:NTimes loop) calculate the
outflow from the reservoir and add this to the Values array at the
appropriate spot (such as ncells/4).
o Proceed with the rest of the calculations as before.
o The resulting AllValues array can be viewed with the same programs
valsurf, plotloc and valmovie.
o How does the flooding compare with the results from an "instant" melting?
2. The above example could be extended to have a reservoir located at every
location (a more realistic model where there would be some amount of snow at
every point along the river) and then the program would do melting and outflow
at each location. To do this, make the reservoir an array and calculate the flow
into the river for every cell.
3. Another modification would be to store the fractions left, right and same in an
array (one element for each cell). These could originally be set to the original
values, but later you could set one cell with fractions left, right and same to be
3/10, 2/10 and 5/10 respectively. This would model a region where the flow
slowed substantially (such as if there was a dam that limited the flow of water in
the river) and see how this changes the resulting flooding both upstream and
downstream of the dam.

Answers to these problems can be found in


http://physics.gac.edu/~huber/envision/tutor2/diffvis.htm

Electronic Copy: http://physics.gac.edu/~huber/envision/tutor2/diffvis.htm


Revised: 6-June-1997 by Tom Huber, Physics Department, Gustavus Adolphus
College.

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