## Basic Matlab## About MatlabMatlab stands for Cleve Moler later founded MathWorks, which continues to expand and market Matlab. Matlab has by now absorbed most of the public domain scientific computation software, and has its own programming language and graphing system. There are interfaces to programming languages, to the Excel spreadsheet, scientific instruments, and much more. There is also an add-on called Simulab for circuit simulation. ISU has a site license for Matlab, and it should be available in every lab on campus. You can probably get a cheap version for your own computer; details change frequently, so check the ISU Information Technology software page. ## Data TypesMatlab has several different data types. The main data type is double, which consists of scalars, vectors and matrices of real or complex numbers. Other data types you may come across are char (strings), sym (symbolic variables), inline (inline function), function_handle (function handles), cell (cell arrays) and struct (structures).
There are others, and you can also develop your own (object-oriented programming). ## Constants and Variables
All matrices start with subscript 1. Commas separate numbers in the same row; semicolons separate rows. Variable names can contain letters, numbers and underscores, for example x, x1 or x_1. The first character has to be a letter or underscore. There is some limit on length, but it is so large that it does not matter in practice. All numbers are internally stored as double precision variables (about 15 decimals of accuracy). ## Predetermined Variablesi ## Basic Matricesx = zeros(3,4) ## StatementsSeparated by comma, end of line, or semicolon. Comma or end of line cause the result to be displayed, semicolon suppresses the result. If you do not assign the result to any variable, it gets automatically assigned to variable ans. y = x + ... % continuation statement ## Important Commandshelp <function> ## Basic Arithmetic Functionsc = a + b
A±B % A, B must be matrices of same size, or scalars ## Pointwise Arithmetic Functions on MatricesC = A.*B Standard functions all work element by element when applied to matrices: C = sin(A), cos(A), exp(A), log(A), etc. ## Use Vector/Matrix NotationTo write good Matlab programs, you have to learn to think in terms of entire vectors and matrices, not in terms of element-by-element computations. Your programs will be shorter and run faster.
for i = 0:100
x = 0:0.1:10; ## Matrix Concatenation
## The Colon Operator and Matrix Subscripting1:10 = [1,2,3,4,5,6,7,8,9,10]; Colon-generated lists are used often in subscripting and loops: A(1:3,2:3) = the 3x2 submatrix taken from rows 1-3, columns 2 and 3 In subscripting, a single colon means "from beginning to end". You can also use the string "end". A(:,2) = second column ## Formatting Output## dispThe disp(whatever) command has precisely the same effect as just typing whatever, except it doesn't put up the labeling.
Note that disp takes a single argument. To display several things, you have to group them together:
To mix text and numbers, use num2str (number to string): >> x ## Displaying a certain number of significant digitsNormally, you only have two choices: format short, which gives you 5 decimals of accuracy, and format long, which gives you 15 decimals. Internally, Matlab keeps full accuracy, this is just a matter of how the numbers are displayed. For finer control, use sprintf (modelled on the sprintf function from the C programming language):
The %12.8f means: display this as a floating point number of 12 characters, 8 of them after the decimal point. That leaves 1 character for the decimal point and 3 characters before the decimal point (in this case 1 digit and 2 leading blanks).
Here %d means "display this as an integer, with however many digits that takes". %2d means "display this as an integer, using 2 characters". Since we only have one digit, we get a leading blank. %2.2d means "display this as an integer using the full 2 characters". That generates leading zeros. ## Control Structures
## Plottingplot(x,y) % connect the dots ## Multiple plots in one picture
Text is interpreted as in TeX (simple cases only, like greek letters, subscripts)
Some other relevant commands are listed below. Instead of print, you can also use the buttons on the figure.
All graphics commands can be executed in the form h
= command. h is the ## WorkspaceThe ## Scripts and FunctionsMatlab knows about
- behaves precisely as if you type the commands at the keyboard
- no input or output arguments
- uses main workspace
- can have input/output arguments (but does not have to)
- has its own workspace => recursive calls are possible
x = 5;
Call them from main program: x = 3;
function [out1,out2,...] = f(in1,in2,...) All input arguments go on the right. All output arguments go on the left. Input and output arguments can have the same name. Functions can be called with more or fewer input or output arguments than defined. Nothing bad happens as long as you don't try to use an undefined value.
function [y1,y2] = f(x1,x2) called as y = f(1,2) % y2 is thrown awayThe following example shows a function norm(x,p) which calculates the p-norm of the vector x. If p is not given, use p=2. This is what the actual built-in norm command does. function y = norm(x,p) Here is an example with a variable number of outputs. This is how the actual built-in command size works:
function s = sum(varargin)
These can be used for simple, one-line functions, if you don't want to deal with creating a file for them. There are two ways to do this:
In this example, f and g are the same function. The 'x','y' at the end of the definition of f, and the (x,y) in the definition of g, means that the first input argument is x, the second is y. If I call f(2,3), then x=2 and y=3. It is not strictly necessary to specify the order, but it is recommended (unless there is only one argument). There is a default ordering of inputs, but the rules are quite complicated. In the following example, f and g are different.
The difference is the following. The formula for f just gets stored when it is defined, and gets evaluated when you call it. When you call f(2,3), you get 2^2 + a*3, but a is undefined inside the workspace of f, and you get an error. The formula for g gets evaluated when it is defined. However, the current value a=5 gets hardwired into g, so g(2,3)=2^2+5*3=19.
Function handles were developed to pass functions as arguments. Suppose you have a function f, stored in a file f.m, and you want to numerically integrate it from 1 to 3. The integration routine is called quad (for "quadrature").
@f is a function handle. You can also do
The syntax from above
is a side effect of this. g is actually a handle for an inline function. ## Paths and Shadowed FunctionsWhat actually happens when you type x = a? - Matlab looks whether there is a variable a in the workspace. If yes, it uses that.
- Matlab checks whether there is a builtin routine named a
- Matlab looks in the path for a function a.m. If there is one, it runs the function (with no arguments), and assigns the result to x
There could be several routines a.m in the path. The order of directories
in the path determines which one
gets executed. The routines after the first one are called When you type x = a(3), the same thing happens. This could be the third element in array a, or function a evaluated with argument 3. Relevant commands are
## Global VariablesSometimes it is necessary for a function to access variables in the main workspace. Main program:
Function:
## Working With PolynomialsPolynomials in Matlab are represented as vectors of coefficients, highest power first. There are a few commands for manipulating them, unfortunately no polyadd.
## Examples:
## Optional Material## Structures and Cell Arrays
A A
This is basically the same as a cell array { 'James Smith', '(515) 555-1234', 60000}, except that the subscripts are 'name', 'phone' and 'salary' instead of 1,2,3. ## Getting Input From the KeyboardThe input command does just that:
## Using the DebuggerThe debugger lets you single-step through your routines. I usually invoke it in one of two ways: - Put the command keyboard in the script or function. Execution will stop there and bring up the debugger.
- Type "dbstop in <routine_name>". Next time you execute that routine, it will bring up the debugger at the first statement.
To get out of it, use dbquit, followed by dbclear all. ## Comments and Help FilesThere are two commands for getting help on built-in commands. If you know what the command is called, use help. If you don't, use lookfor. Here is what they actually do: Comment lines start with a percent sign. The lookfor command goes through every single *.m file in the path, reads the first comment line, and checks it for a string match with what you are looking for. The help command looks at the particular file you are asking for, and lists the first unbroken string of comment lines it finds. Consider this:
If you follow Matlab's conventions, your own routines will fit right in with the Matlab help system: - The first comment line contains the name of the routine in uppercase, followed by a one-line description
- The following comment lines give an example of how to call it, and what the input and output arguments mean. You can also add details on the algorithm, etc.
- Any comments you don't want listed (like my copyright notice) are separated by a blank line from the rest.
There is one more kind of documentation you can do. Suppose we guessed (correctly) that the routine for doing a QR decomposition is called qr. We see that this routine is in a directory called matfun, and wonder what other things might be in there. Of course you could go there and look, but there is an easier way:
This is done by placing a file called Contents.m in that directory. The file contains nothing but comments, which are listed when you type help matfun. Last Updated: July 31, 2014 |