New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Miss Adeline Weimann


Miss Adeline Weimann
GPA 3.57


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in Economcs

This 12 page Class Notes was uploaded by Miss Adeline Weimann on Wednesday September 9, 2015. The Class Notes belongs to ECON 502 at University of Washington taught by Staff in Fall. Since its upload, it has received 14 views. For similar materials see /class/192481/econ-502-university-of-washington in Economcs at University of Washington.




Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/09/15
ECON 502 INTRODUCTION TO MATLAB Nov 9 2007 TA Murat Koyuncu 0 What is MATLAB1 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 MATLAB is designed to solve problems numerically that is in finite precision arithmetic Therefore it produces approximate rather than exact solutions and should not be confused with a symbolic computation system SCS such as Mathematica or Maplez It should be understood that this does not make Matlab better or worse than an SCS it is a tool designed for different tasks and is therefore not directly comparable 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 1 Finding Your Way Around MATLAB Double click on the MATLAB icon on your desktop The MATLAB Desktop will openithis is the Graphical User Interface for MATLAB The desktop you see may include only one window or may have two or three One of the windows within the desktop or the only one you see is called the Command window This is where you will most often interact with MATLAB A prompt gtgt is displayed in the Command window followed by a blinking cursor which lets you know that MATLAB is ready to accept your commands Try typing the following gtgt exl ones2 The output should look like this exl 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 gtgt format compact 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 7 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 11 Help System Easiest way to get help in MATLAB is to click on the question mark on the toolbar This invokes the help system of the software where you could go through the contents of its manual search for certain keywords and even watch some demos about how to use MATLAB If you know the name of a Matlab function you need help with type gtgt help functioniname 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 We39ll be introducing matrix style operations along with their scalar counterparts so you can understand the patterns that arise in the syntax 21 Simple Math MATLAB can do simple math just like a calculator try typing gtgt iOl3 Now hit Enter ans 23 MATLAB evaluates the command and returns the answer ans You can also store the numbers as variables and operate on them gtgt numl 10 numl 10 gtgt numZ 13 gtgt numl numZ 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 Another point is that usage of lowercaseuppercase letters matters in MATLAB gtgt NumlelO Undefined function or variable 39Numl39 Standard order of operations would apply when a string of calculations are typed up gtgt 3A2t471 ans 35 So use parenthesis if you need a certain order gtgt ans14 ans 22 Builtin Functions MATLAB has hundreds of pre defined functions that you can use in your computations Among them are trigonometric and inverse trigonometric functions sin cos asin acos at an etc exponential function exp logarithm functions 1 0g is log to base e While logl O and logZ are logs to bases 10 or 2 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 3 Vectors and Matrices 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 9 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 gtgt A 1 2 3 l 9 To create a column vector separate each element by a semicolon gtgt B 4 5 6 l 9 To enter a matrix combine the row and column notation gtgtC l 4 98 4 72 6 3 C l 4 9 8 4 7 2 6 3 gtgtG 42 85 9 l4 l3 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 gtgt C23 Displays the element in the 2nd row and 3rd column of C ans 3 Note that anything typed after a sign is not evaluated Use this feature frequently When writing programs in MATLAB gtgt C3 Displays the 3rd column of C gtgt C2 Displays the 2nd row of C The colon tells MATLAB to include all rows or columns To extract a smaller sized matrix from an existing matrix use the address of the desired elements gtgt Cl223 Displays the first two elements of the 2nd and third column ans 4 9 4 7 To extract the main diagonal use the di ag command gtgt Cdiag diagC Cdiag l 4 3 To delete rows and columns from a matrix use just a pair of square brackets C 1 9 8 7 2 3 Three special matrices that you ll often use are the zero matrix the identity matrix and matrixesVectors of ones gtgt DZeros33 disp1ays a 3x3 matrix of zeros gtgt Eeye44 disp1ays a 4x4 identity matrix gtgt Fones31 disp1ays a 3x1 matrix of ones 31 Manipulating Matrices The symbols for basic arithmetic operations with matrices are nadm mriegqgtgt CG 7 nsumnw mrieggtgt C76 nnn mnn mrieggtgt CtG inv ninva ngarnm x gtgt Cinv inVC Cinv 701034 01448 700276 700345 700517 02241 01379 00069 700966 or for divisionieg gtgt C G or GC for right division or left division Note that matrices must be conformable for these operations to be defined Also note that C G CtinvGand thC invGCWhnmznegenaa ynotmesmne Other useful operators include 39 for transpositionieg gtgt C 39 det for the determinantiegq gtgt det G trace for the traceieg gtgt trace G eig for the eigenvaluesieg gtgt eig G 31 Concatenation MATLAB can easily join matrices together to make a larger matrix gtgtA3 7 45 9 24 6 1 gtgtB A A12 At3 A2 B 30000 70000 40000 150000 190000 160000 50000 90000 20000 170000 210000 140000 40000 60000 10000 160000 180000 130000 90000 210000 120000 15000 35000 20000 150000 270000 60000 25000 45000 10000 120000 180000 30000 20000 30000 05000 312 ElementbvElement Operations Sometimes it s useful to have MATLAB perform an operation on each element of a matrix For example gtgtAA2 Performs the usual matrix multiplication AtA gtgtAA2 Squares each element of the matrix A MATLAB can also perform element by element multiplicationieg A 2 e and diViSiOHi eg A 2 or equivalently 2 A 32 Solving Linear Equations X AB Denotes the solution to the matrix equation AX B X BA Denotes the solution to the matrix equation XA B 4 Writing Simple Programs The capabilities of Matlab can be extended through programs written in its own programming language It provides the standard constructs such as loops and conditionals these constructs can be used interactively to reduce the tedium of repetitive tasks or collected in programs stored in m filesquot nothing more than a text file with extension m 41 Script M les If you just want to enter in some simple problems for MATLAB to solve using the Command window is fast and easy But you will often have a long sequence of commands on many variables for MATLAB to evaluateisometimes for hundreds of repetitions MATLAB allows you to type your commands in a text file called a script or MFile and then have the commands in the M le evaluated just as if they were entered in the Command window To create an MFile click on the New M file icon on the MATLAB desktop toolbar or choose NewMFile from the File menu You can use the text window that appears to enter commands Try entering Mefile example 10090 7 written by yourname numl 10 numZ 1 3 numlnum2 A1 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 le as dialog box to name and save your file In the CSSCR lab save your MFile 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 42 For Loops A For Loop executes a set of commands a given number of times Try running this simple program from an M File clear this clears all variables from the workspace nlO betazerosnl Create an nxl vector to hold Beta vector for il n set of times to execute the following commands betailil formula for the ith element of beta end end the For loop beta print beta in the command window 43 While Loops A While Loop executes a set of commands repeatedly until a controlling expression is no longer true clear bOtO Enter the initial values of variables b and t while 2Ablt200 Enter the controlling expression bbi tt2Ab These two lines are the commands to be executed end End the While Loop 44 I fElseEnd Conditional The lf Else End construct evaluates a logical expression and executes a command or group of commands based on the value of that expression Try running this simple program from an M Idle clear brandn pick b from the NOl distribution if bgtO countl The variable count will be equal to 1 if bgtO else countO count is zero otherwise count show count in the command window These constructs can be used together or nested within themselves andor one another allowing you to write powerful programs in which the results of past calculations affect subsequent operations 45 The Current Directory and Search Path To use an MFile that you have created MATLAB needs to know where to find it MATLAB looks on a Search Path so you need to make sure that the directory in which you saved your M File is on this path The easiest way to do this is to make the directory in which you ve saved your M File the Current Directory 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 gtgt path path directory39 For example in the Econ grad computer lab you would type gtgt path path z 39 when logged on with your userid 46 Function MFiles These M Files differ from the script M Files you ve been working with in that they accept input arguments and return output arguments A Function M File operates on variables contained within its own workspace which is separate from the workspace you ve been accessing from the command line or through script M Files To write a function M File open a new M File and type the following function xtestlaB x is the output argument from the function quottestlquot a and b 10 are its input arguments xa39Ba23 define x as a function of the input arguments Now save your function M Fileiyou must save your file With exactly the same name you gave the functionitestlm 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 ithe function will operate on any conformable inputs that you give it In the command Window type the following gtgtc23 gtgtD3 68 4 c and D are the input arguments for testl Now call your function by typing gtgttest1cD 5 Plotting Graphs MATLAB has powerful graphing features To get started plotting graphs try this example of a simple 2 D graph n150 hln XOhl this means x starts at O and goes to 1 by increments of h ysin2pix plotXy The plot command title39Graph of ysin2pix39 Give the graph a title xlabel39x axis39 ylabel39y axis39 Label the axes When the graph appears use the menu and toolbar to modify it andor copy and paste it into a Word document 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 ias Ci 1 gtgt 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 gtgt save C exampleFileAll fascii This saves all variables in the Workspace in a ASCII file in the directory C Now let s clear all variables in the workspace gtgt clear all Loading data from a mat file is easy Just use 39 l oad 39 instead of the command 39 s ave 39 gtgt load exampleFile A B 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 quotI oad exampleFi le A quick method of importing text or binary data from a file eg Excel files is to use the MATLAB Import Wizard Open the Import Wizard by selecting File gt 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


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.