What Is MATLAB?: ECON 502 Introduction To Matlab Nov 9, 2007 TA: Murat Koyuncu
What Is MATLAB?: ECON 502 Introduction To Matlab Nov 9, 2007 TA: Murat Koyuncu
What Is MATLAB?: ECON 502 Introduction To Matlab Nov 9, 2007 TA: Murat Koyuncu
0. What is MATLAB?1
MATLAB stands for matrix laboratory and is one of the most popular software for numerical
computation. MATLAB’s basic data element is an array (or matrix), which makes programming
to solve problems involving vector and matrix formulations (like those found in dynamic
equation systems of macro and econometrics) fairly straightforward.
The following is a brief introduction to MATLAB aimed at getting you up and running. You
will almost certainly need to spend time at your computer with the MATLAB manual, help tools
of the program itself, and any other reference book you can find on the topic.
ex1 =
1 1
1 1
1
This document is compiled from various resources. So almost all errors are theirs.
2
Actually, there is a Symbolic Math Toolbox in MATLAB that carries out symbolic computations, but it is much
less sophisticated than Mathematica or Maple.
This represents a 2x2 matrix of ones. Matlab inserts extra blank lines between practically
everything. To turn off this feature, type
To the left of the command window, we see Workspace and Current Directory window. While
the first shows the variables that are currently in MATLAB’s memory, second one simply shows
the contents of the folder that you are working in. The Workspace window shows you the
variables that you have created and, most notably, their dimensions. A variable in the
Workspace is available for use. On the bottom left you have Command History window – this is
where past commands are remembered. If you want to re-run a previous command you can
double click on it from this window (Right click on the command for more options.)
If you know the name of a Matlab function you need help with, type
>> help function-name
to see the help text contained in the function definition itself on Command window. This is a
better method for quick reference.
2. Syntax
Matlab works by executing the mathematical statements you enter in the command window. By
default, any output is immediately printed to the window.
You are also allowed to assign a name to an expression for your convenience. Keep in mind that
the name you assign is only a name, and it does not represent a mathematical variable (as it
would in Maple, for example). Every name must have a value at all times. If you try to read the
value of an unassigned name, you will get an error.
Nearly everything in Matlab is a matrix, whether it looks like it or not. This takes some getting
used to. We'll be introducing matrix-style operations along with their scalar counterparts so you
can understand the patterns that arise in the syntax.
2
2.1 Simple Math
MATLAB can do simple math just like a calculator; try typing:
>> 10+13
ans =
23
MATLAB evaluates the command and returns the answer (ans =). You can also store the
numbers as variables and operate on them:
>> num1 = 10
num1 =
10
ans =
23
Note that MATLAB didn’t show that “num2 = 13” when you entered that variable. The
semicolon at the end of the command line tells MATLAB to evaluate the command but not
display the answer.
>> Num1-10
Standard order of operations would apply when a string of calculations are typed up.
>> 3^2*4-1
ans =
35
3
So use parenthesis if you need a certain order:
>> (ans+1)/4
ans =
Matlab also has many other more sophisticated functions for solving linear equations, getting
eigenvalues of matrices, solving differential equations or calculating integrals numerically. Help
button is your friend!
Matlab is most used to work with matrices and vectors. Vectors are either row vectors or column
vectors and it is usually important to be clear as to what kind of vector you mean.
To create a row vector enter the name for the vector and the elements of the vector separated
by spaces (or commas) surrounded by square brackets.
>> A = [1 2 3]
>> B = [4;5;6]
C =
1 4 9
8 4 7
2 6 3
4
To extract parts of a matrix you can use one of the following commands:
- to display (or operate) on a particular element, row, or column of a matrix use its
address. The general syntax is matrixname(row#,column#).
>> C(2,3) %Displays the element in the 2nd row and 3rd
column of C.
ans =
Note that anything typed after a % sign is not evaluated. **Use this feature frequently when
writing programs in MATLAB!
- To extract a smaller sized matrix from an existing matrix use the address of the
desired elements:
ans =
4 9
4 7
Cdiag =
To delete rows and columns from a matrix use just a pair of square brackets:
5
>> C(:,2)=[]
C =
1 9
8 7
2 3
Three special matrices that you’ll often use are the zero matrix, the identity matrix and
matrixes/vectors of ones.
Cinv =
/ or \ for division—e.g., >> C/G or G\C for “right” division or “left” division
Note that matrices must be conformable for these operations to be defined. Also note that C/G
= C*inv(G) and that G\C = inv(G)*C, which are generally not the same.
6
Other useful operators include:
3.1.1 Concatenation:
B =
Sometimes it’s useful to have MATLAB perform an operation on each element of a matrix. For
example,
7
3.2 Solving Linear Equations
X = A\B: Denotes the solution to the matrix equation AX = B.
To create an M-File, click on the New M-file icon on the MATLAB desktop toolbar, or choose
New/M-File from the File menu. You can use the text window that appears to enter commands.
Try entering
num1 = 10
num2 = 13;
num1+num2
A=[1 2 3]
Now click the Run icon on the toolbar to execute your commands. MATLAB asks you to save
your file before it is run; use the Save file as: dialog box to name and save your file. In the
CSSCR lab, save your M-File to the /temp folder. (MATLAB may open a dialog box asking
about your Current Directory, if so, select the option that changes your Current Directory to the
/temp folder where you’ve saved your M-File.)
The results of running your M-File appear in the MATLAB command window.
8
clear; %this clears all variables from the workspace
n=10;
clear;
b=b+1;
clear;
9
if b>0
else
end
These constructs can be used together, or nested within themselves and/or one another, allowing
you to write powerful programs in which the results of past calculations affect subsequent
operations.
Alternatively, you can put that directory on the Search Path by selecting Set Path in File menu
or by typing the following in the Command window:
For example in the Econ grad computer lab you would type
10
%are its input arguments
Now save your function M-File—you must save your file with exactly the same name you gave
the function—test1.m in this example (make sure you save it to either the current directory or a
directory that is on the search path). In the command window, enter any conformable “a” and
“B” (note: you do not need to name them “a” and “B”—the function will operate on any
conformable inputs that you give it). In the command window type the following:
>>c=[2;3];
>>D=[3 6;8 4]; %c and D are the input arguments for test1
>>test1(c,D);
x =
155
5. Plotting Graphs
MATLAB has powerful graphing features. To get started plotting graphs, try this example of a
simple 2-D graph.
n=150;
h=1/n;
%by increments of h
y=sin(2*pi*x);
When the graph appears, use the menu and toolbar to modify it and/or copy and paste it into a
Word document.
11
6. Working With Data
You will certainly need to export your results from MATLAB or import data from other sources.
Let’s start by saving some of what we did until now. The basic command format is the save
command followed by the name of the file to create. This is followed by a list of the variables
which are to be saved in the file. To create an ASCII file which can be read by a spreadsheet the
list of variables is followed by the command –ascii.
>> save exampleFile A B C This saves the A, B, and C variables in a MATLAB data
file (with .mat extension) in the current directory.
>> save C:/exampleFileAll -ascii This saves all variables in the Workspace
in a ASCII file in the directory C.
Loading data from a .mat file is easy. Just use ’load’ instead of the command ’save’.
Note that you can choose which variables to load. This command loads only A and B, if you
wanted to load all variables you could simply write “load exampleFile”.
A quick method of importing text or binary data from a file (e.g., Excel files) is to use the
MATLAB Import Wizard. Open the Import Wizard by selecting File -> Import Data at the
Command Window.
Specify or browse for the file containing the data you want to import and you will see a preview
of what the file contains. Select the data you want and click Finish. (For more information, see
Help file for ‘Importing Text Data’)
12