Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

A Tour of MATLAB - Seminar in Mathematics - Lecture Notes | MATH 496, Study notes of Mathematics

Material Type: Notes; Class: Seminar in Mathematics; Subject: Mathematics ; University: University of Nebraska - Lincoln; Term: Spring 2006;

Typology: Study notes

Pre 2010

Uploaded on 08/31/2009

koofers-user-rcz
koofers-user-rcz 🇺🇸

5

(1)

10 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
A Tour of Matlab for Math 496, Section 6
Thomas Shores
Department of Mathematics
University of Nebraska
Spring 2006
What is Matlab?
Matlab is
1. An interactive system for numerical computation.
2. A programmable system for numerical computation.
3. A front-end for state-of-the-art libraries, currently LAPACK and optimized BLAS.
4. NOT a CAS (computer algebra system). Matlab has an add-on Symbolic package, but the
base system is not made to do symbolic mathematics or exact arithmetic like Maple or a
TI-89. All calculations are in IEEE double precision floating point numbers.
History:
Late 70s: Cleve Moler writes Matlab under an NSF grant as a front-end for the current
state-of-the-art numerical linear algebra packages LINPACK and BLAS.
Early 80s: Moler founds the MathWorks and introduces a commercial version of Matlab
running on a PC and written in Fortran.
Early 90s: Matlab is rewritten in C and “handle graphics” is added into Matlab.
Late 90s: Matlab evolves into an OOP supporting LAPACK and optimized BLAS.
An excellent reference for this material is the superb text (recommended but not required) by
Desmond Higman and Nicholas Higman, Matlab Guide, SIAM, Philadelphia, 2000.
A Tutorial Introduction to Matlab
Here we go.... Our procedure in all the lectures will be to work our way through the commands
that are listed in the narrative that follows. Separately one should open a Matlab window for
command execution. The prompt sign “> and typewriter text indicate a command to be typed in
by the instructor or reader at the Matlab command prompt. Comments will not be preceded by the
prompt and will appear in normal text. I will make comments on the commands that are executed
as we read through the lecture, and students are invited to ask questions as we proceed. In the
body of the Matlab command listing there will be occasionally a “%” sign. This is Matlab’s way
of starting a comment, and all text until the next end of line is ignored by the Matlab interpreter. It
isn’t necessary to type in these comments in order to work through this lesson in a Matlab session.
They are inserted to give a little more explanation to the meaning of the commands for those who
are reading this file and executing the commands themselves.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download A Tour of MATLAB - Seminar in Mathematics - Lecture Notes | MATH 496 and more Study notes Mathematics in PDF only on Docsity!

A Tour of Matlab for Math 496, Section 6

Thomas Shores Department of Mathematics University of Nebraska Spring 2006

What is Matlab?

Matlab is

  1. An interactive system for numerical computation.
  2. A programmable system for numerical computation.
  3. A front-end for state-of-the-art libraries, currently LAPACK and optimized BLAS.
  4. NOT a CAS (computer algebra system). Matlab has an add-on Symbolic package, but the base system is not made to do symbolic mathematics or exact arithmetic like Maple or a TI-89. All calculations are in IEEE double precision floating point numbers.

History:

  • Late 70s: Cleve Moler writes Matlab under an NSF grant as a front-end for the current state-of-the-art numerical linear algebra packages LINPACK and BLAS.
  • Early 80s: Moler founds the MathWorks and introduces a commercial version of Matlab running on a PC and written in Fortran.
  • Early 90s: Matlab is rewritten in C and “handle graphics” is added into Matlab.
  • Late 90s: Matlab evolves into an OOP supporting LAPACK and optimized BLAS.

An excellent reference for this material is the superb text (recommended but not required) by Desmond Higman and Nicholas Higman, Matlab Guide, SIAM, Philadelphia, 2000.

A Tutorial Introduction to Matlab

Here we go.... Our procedure in all the lectures will be to work our way through the commands that are listed in the narrative that follows. Separately one should open a Matlab window for command execution. The prompt sign “> ” and typewriter text indicate a command to be typed in by the instructor or reader at the Matlab command prompt. Comments will not be preceded by the prompt and will appear in normal text. I will make comments on the commands that are executed as we read through the lecture, and students are invited to ask questions as we proceed. In the body of the Matlab command listing there will be occasionally a “%” sign. This is Matlab’s way of starting a comment, and all text until the next end of line is ignored by the Matlab interpreter. It isn’t necessary to type in these comments in order to work through this lesson in a Matlab session. They are inserted to give a little more explanation to the meaning of the commands for those who are reading this file and executing the commands themselves.

How to handle a Matlab assignment

Well, do it, of course. The real question is: how do I turn it in? I suggest that you start up Matlab and do the work you need to do. Once you actually knew what you’re doing, redo it with an eye to recording your work and turning it in to me. To keep a recording of your work, you issue the following command to Matlab

diary ’myfile’ (Caution: make sure your current working directory is a place where you can write files – use the icons above the workspace area to change working directories.) Matlab will then send a copy of all your typed input and the output to a file called ’myfile.’ For clarity, use descriptive names for your files, such as ’jsmithasgn1’ so that when I save the files that you email me, I can tell what it’s about by the title. If at any point you want to stop the diary feature, issue the command diary off To resume the diary feature, simply type diary on This will cause input to be appended to myfile. You can make comments in your homework file by typing % at the command line and this too will be recorded. For example % This is a comment. Be sure to start your file with the comments % Name: yourname % Email: your email address When you end your session, the file will be closed and you can view it and even edit it with a text editor. As a matter of fact, you can even edit and view it with the Matlab Editor. Just type edit myfile When you have finished the assignment, email the file to me as an attachment. My email address is tshores@math.unl.edu. That’s all there is to it! Now for the tutorial. I covered a good deal of this in class (1/12/05). Read it at your leisure and do enough of the commands that you are starting to get comfortable with Matlab.

Starting and stopping

Start up Matlab and quit after a few calculations and getting some help.

1+ 1+1; pi % to get help on a command or built-in variable just type: help pi % get help on built-in variable pi help quit % get help on built-in common helpwin % or get help browser style quit

A calculator

Restart and do the following:

x=0.

y = x .* sin(x); plot(x,y) % close the plot window, then plot(x,y) hold on plot(x, x.*sin(x))

Functions and scripts

There are two kinds of text files that can be “run” under Matlab, both of which have the suffix “.m” The first kind is a script file. This file contains a list of commands that one could execute at the command line. It is rather like a program in C or Fortran, but not as capable. For one thing, there is no division of program into a “main” section and various subroutines. You cannot include function definitions in a script file. For example, in your Matlab session check the current working directory to make sure that it in one in which you want to save files – like a MatlabFiles directory in you account – and issue the command

edit MyFirstScript; Now enter these lines % name: MyFirstScript.m % description: my first script uservar = input(’Give me a variable and press enter: ’) disp(’This is what you gave me: ’) disp(uservar); Save this file and run your script by issuing the command MyFirstScript That’s all there is to it. The second kind of m file is a function file, which is used to define a value returning subroutine. You announce to Matlab that this file is going to be a function file by making the first line a function definition statement. Issue the command edit fibonacci; Now enter these lines

% function retval = fibonacci(n) % usage: y = fibonacci(n) % description: this function accepts a positive integer % input n and returns a row vector whose entries are the % first n Fibonacci numbers.

% minimal bulletproofing if (n <= 1) retval = 1; elsif (n <= 2) retval = [1 1] else retval = ones(1,n); for jj = 3:n

retval(jj) = retval(jj-1) + retval(jj-2); end % for loop end % if statement

Now run your script and get help on it by entering

fibonacci(6) x = fibonacci(7) help fibonacci

Numbers

Start Matlab. As we indicated in the first lecture, Matlab is a fine calculator. But as with any calculator, one has to be careful:

((2/7+1000)-1000)-2/ Multiple commands are possible x=sin(.3),y=cos(.3);x^2+y^ 2 And of course help is always available, specific or general: help sqrt helpwin There is another handy facility that is a word search function: lookfor elliptic One always has access to the last output: exp(-3) x=ans; disp(x) And one can always load and save variables: save ’junkfile’ x y % Now clear all variables: clear who load ’junkfile’ x who

Arithmetic

Now a few words about arithmetic, which conforms to double precision IEEE standard. Here eps is the distance from 1 to the next floating point number:

eps 1+eps format long 1+eps format hex 1 1+eps 1+2*eps

> A(1,3)

One can access a vector (row or column) by a single coordinate:

y = x’ % the prime sign ’ performs (Hermitian) transpose operation x(3) y(4) = 7 One can build matrices in blocks: b = [eye(3) a; a eye(3)] c = repmat(b,2,3) The all-important colon notation gets used in two different ways. First as a separator in a type of vector constructor: x = 1: y = 1:2: z = (1:0.5:5)’ The other principle use if the colon notation is to work as a wild card of sorts. The colon in a position used for a row indicator means c = b(:, 3:5) Matrix manipulations: triu(a) tril(a) diag(a) diag(diag(a)) reshape(a,1,9) Matrix constructions (there is a huge number of special matrices that can be constructed by a special command.) A sampling: toeplitz((1:5),(1:5).^2) hilb(6) vander((1:6)) Multidimensional arrays: Matlab can deal with arrays that are more than two dimensional. Try the following a = [1 2; 3 4] a(:,:,2) = [1 1;2 2] a A final note on matrices: one can even use a convenient Array Editor to modify matrices. Do this: if the Workspace window is not already visible, click on the View button, then check Workspace. Now double-click on the variable ’a’, a matrix we created earlier. The Array Editor will open up. Edit a few entries and close the Editor. Confirm your changes by typing at the command line: a

Objects

Objects are instances of classes. For now we’re going to confine our attention to some fairly simple types of objects. Matlab has five built-in classes of objects, one of which we’ve already seen:

  • double: double-precision floating point numeric matrix or array
  • sparse: two-dimensional real (or complex) sparse matrix
  • char: character structure
  • struct: structure array
  • cell: cell array

Various Matlab toolboxes provide additional class definitions. Of course, we’ve seen lots of doubles. Here’s another very familiar sort of object, namely a string object: s = ’Hello world’ size(s) s disp(s) The struct object is what it sounds like, a way to create structures and access them. There are two ways to build a structure: command line assignments or the struct command. What actually gets constructed is a structure array. Try the following

record.name = ’John Doe’ record.hwkscore = 372 record.ssn = [111 22 3333] record record(2).name = ’Mary Doe’; record(2).hwkscore = 40; record(2).ssn = [222 33 4444]; record record(1).hwkscore Finally, a cell object is an array whose elements can be any other object. For example: A(1,1) = {[1 2; 3 4]}; A(1,2) = {’John Smith’} A(2,1) = {249} A(2,2) = {[1;2;3;4]} A{1,2} A(1,2)

Basic Graphics

Start Matlab. We’ll plot as usual, but get help to guide us along. The plot command has many options. We’ll hit the highlights. We’ll also keep a help window open so we can peruse the help files as we go. After we open it, we’ll move it to a corner. helpwin Now click on plot in the Help Window and examine the possibilities for the 1-3 character string S. x = 0:0.01:1; % create array of abscissas and suppress output y1 = 4x.(1- x); plot(x, y1, ’r+:’) A plot with multiple curves is possible without doing a “hold on”:

Multiple plots

Here is the way to construct multiple plots, along with another variation on plot: subplot(2,2,1) plot(x,y1) subplot(2,2,2) fplot(’sin(x)’, [0 1]) subplot(2,2,3) fplot(’sin(round(2pix))’, [0 1], ’r--’) subplot(2,2,4), polar(x,y2) There is a whole lot more that you can do with figures. Get help in Matlab on plot. Another interesting aspect of graphics in Matlab is that you can use interactive tools in the Plot window to massage your graphics in many ways. You can also save your graphics from this window. Of course, anything that you can do with the Matlab graphics gui you can also do at the console with the appropriate commands.