Sei sulla pagina 1di 50

MATLAB Tutorial

Getting Started with Calculations, Graphing and Programming

Nicholas R. Kirchner
University of Minnesota

Thursday, August 30, 2012

Outline
1

MATLAB installation

NRK (University of Minnesota)

MATLAB

2012.08.30

2 / 28

Outline
1 2

MATLAB installation The MATLAB UI

NRK (University of Minnesota)

MATLAB

2012.08.30

2 / 28

Outline
1 2 3

MATLAB installation The MATLAB UI Calculations with MATLAB Standard Calculations and Variables Matrices and Vectors

NRK (University of Minnesota)

MATLAB

2012.08.30

2 / 28

Outline
1 2 3

MATLAB installation The MATLAB UI Calculations with MATLAB Standard Calculations and Variables Matrices and Vectors Graphing

NRK (University of Minnesota)

MATLAB

2012.08.30

2 / 28

Outline
1 2 3

MATLAB installation The MATLAB UI Calculations with MATLAB Standard Calculations and Variables Matrices and Vectors Graphing Programming Functions Scripts

4 5

NRK (University of Minnesota)

MATLAB

2012.08.30

2 / 28

Outline
1 2 3

MATLAB installation The MATLAB UI Calculations with MATLAB Standard Calculations and Variables Matrices and Vectors Graphing Programming Functions Scripts Yahoo! Finance

4 5

NRK (University of Minnesota)

MATLAB

2012.08.30

2 / 28

Installing MATLAB

As a MFM student, you pay the CSE Labs fee, and are therefore entitled to a free MATLAB license for your personal computer. Visit https://wwws.cs.umn.edu/account-management/ and open your CSE Labs account. Now, visit https://wwws.cs.umn.edu/matlab/student/, log in, and follow the steps for downloading MATLAB.

NRK (University of Minnesota)

MATLAB

2012.08.30

3 / 28

Installing MATLAB (cont.)

(Place holder slide)

NRK (University of Minnesota)

MATLAB

2012.08.30

4 / 28

MATLAB window

1 2

Command Window. Input commands (2+8), get output (ans = 10). Current Folder. Contents of current directory.
MATLAB 2012.08.30 5 / 28

NRK (University of Minnesota)

MATLAB window (cont.)

3 4

Workspace. Lists your variables and functions as you dene them. Command History. Shows previous commands.
MATLAB 2012.08.30 6 / 28

NRK (University of Minnesota)

Math on Real Numbers


Arithmetic in MATLAB works roughly the way youd expect it to, in the sense that the operations +, -, *, /, and paraentheses obey the usual order of operations. Expression to compute
2 (610)2

Input to MATLAB 2/(6-10)^2 + 4 log(3^4) exp(5) log10(3^4)

Output ans=4.1250 ans=4.3944 ans=148.4132 ans=1.9085

+4

ln(34 ) e5 log10 (34 ) 3e 0.6 4

NRK (University of Minnesota)

MATLAB

2012.08.30

7 / 28

Math on Real Numbers


Arithmetic in MATLAB works roughly the way youd expect it to, in the sense that the operations +, -, *, /, and paraentheses obey the usual order of operations. Expression to compute
2 (610)2

Input to MATLAB 2/(6-10)^2 + 4 log(3^4) exp(5) log10(3^4)

Output ans=4.1250 ans=4.3944 ans=148.4132 ans=1.9085

+4

ln(34 ) e5 log10 (34 )

3*exp(0.6)-4 ans=1.4664 3e 0.6 4 Note that in MATLAB, log(x) means the natural logarithm (base e ).

NRK (University of Minnesota)

MATLAB

2012.08.30

7 / 28

Variables

MATLAB has been reporting its results in the form ans = .... ans is a variable. For example, the input 2*21 sets ans to 42.

NRK (University of Minnesota)

MATLAB

2012.08.30

8 / 28

Variables

MATLAB has been reporting its results in the form ans = .... ans is a variable. For example, the input 2*21 sets ans to 42. To add three to the previous result, we can issue the command ans+3. MATLAB will look up the value of ans and add 3 to it. The output ans = 45 indicates that the variable ans has now been given the value 45. A variable is a place MATLAB sets aside in memory to hold a value.

NRK (University of Minnesota)

MATLAB

2012.08.30

8 / 28

Variables

MATLAB has been reporting its results in the form ans = .... ans is a variable. For example, the input 2*21 sets ans to 42. To add three to the previous result, we can issue the command ans+3. MATLAB will look up the value of ans and add 3 to it. The output ans = 45 indicates that the variable ans has now been given the value 45. A variable is a place MATLAB sets aside in memory to hold a value. We can make our own.

NRK (University of Minnesota)

MATLAB

2012.08.30

8 / 28

Variables (cont.)

Issuing the command fred = log(42) denes a new variable named fred and gives it the value 3.7377. The command 5*fred then multiplies 5 by whatever fred is. In this case, the output is 18.6883. MATLAB shows you a list of values in the Workspace. Variable names are case sensitive. The commands a=2 and A=7 dene two dierent variables.

NRK (University of Minnesota)

MATLAB

2012.08.30

9 / 28

Matrices and Vectors, Denitions


MATLAB is short for MATrix LABoratory. It was built for high-speed matrix calculations. We will dene the following 1 2 3 2 0 4 12 A = 4 5 6 , B = 3 5 1 , C = 4 2 8 , D = 6 7 8 9 2 1 0 7 Issue the following commands:

NRK (University of Minnesota)

MATLAB

2012.08.30

10 / 28

Matrices and Vectors, Denitions


MATLAB is short for MATrix LABoratory. It was built for high-speed matrix calculations. We will dene the following 1 2 3 2 0 4 12 A = 4 5 6 , B = 3 5 1 , C = 4 2 8 , D = 6 7 8 9 2 1 0 7 Issue the following commands: >> >> >> >> A B C D = = = = [1,2,3;4,5,6;7,8,9] [2,0,4;-3,5,1;-2,1,0] [-4,2,8] [12;6;-7]

NRK (University of Minnesota)

MATLAB

2012.08.30

10 / 28

Matrices and Vectors, Standard Operations

Issue the commands A*B and B*A. What do you notice? Try the commands A*C and A*D. Compute the matrix inverse of B , using the inv command. Compute the determinant of A. Compute B 1 D . Dene E as below, without using E = [7,0,0;0,7,0;0,0,7]. Get acquainted with the help menu if you need to. 7 0 0 E = 0 7 0 0 0 7

NRK (University of Minnesota)

MATLAB

2012.08.30

11 / 28

Matrices and Vectors, Editing Components


You can edit a matrix variable by double-clicking that variable name in the Workspace. This brings up a spreadsheet-like interface to edit the matrix.

In the Command Window, issue the following commands: >> >> >> >> >> A(3,2) A(3,2) = 37 A(3,:) A(:,2) A(:,2) = [10;11;12]

What did they do?


NRK (University of Minnesota) MATLAB 2012.08.30 12 / 28

Matrices and Vectors, Elementwise Operations


Often, we want to do the same thing to each component of a matrix. MATLAB makes this straightforward. Issue the command log(D) to take the natural log of each element of D . Exercise: Multiply each element of C by 3, and add 9

NRK (University of Minnesota)

MATLAB

2012.08.30

13 / 28

Matrices and Vectors, Elementwise Operations


Often, we want to do the same thing to each component of a matrix. MATLAB makes this straightforward. Issue the command log(D) to take the natural log of each element of D . Exercise: Multiply each element of C by 3, and add 9 MATLAB interprets * and ^ as matrix multiplication and exponentiation. For elementwise operations: Multiplying C and D elementwise is done with the command C .* D. Squaring each element of C is done with the command C .^ 2. Exercise: Find the dot product of C and D . Exercise: Compare A * B and A .* B. Exercise: Compare B ^ 3 and B .^ 3.

NRK (University of Minnesota)

MATLAB

2012.08.30

13 / 28

Graphing Data

MATLAB draws graphs by taking two vectors, one for the independent variable and one for the dependent variables, and plotting the corresponding points. Try the following sequence of commands: >> x = [1,2,3,4,5,6] >> y = [2,5,4,4,7,11] >> plot(x,y,--rs)

NRK (University of Minnesota)

MATLAB

2012.08.30

14 / 28

Graphing Data

MATLAB draws graphs by taking two vectors, one for the independent variable and one for the dependent variables, and plotting the corresponding points. Try the following sequence of commands: >> x = [1,2,3,4,5,6] >> y = [2,5,4,4,7,11] >> plot(x,y,--rs) Exercise: Try omitting various parts of the rs. Can you make your graph use green squares and no lines?

NRK (University of Minnesota)

MATLAB

2012.08.30

14 / 28

Graphing Functions

Lets make a graph of y = sin(x 2 ) on the interval 5 x 5. First create an x vector: x = [-5:0.1:5]. What did this command do? plot(x,sin(x.^2)) gives us the graph. Notice the elementwise exponentiation. (Exercise: replace x.^2 with x^2, and understand the cause of the error.)

NRK (University of Minnesota)

MATLAB

2012.08.30

15 / 28

Graphing Functions

Lets make a graph of y = sin(x 2 ) on the interval 5 x 5. First create an x vector: x = [-5:0.1:5]. What did this command do? plot(x,sin(x.^2)) gives us the graph. Notice the elementwise exponentiation. (Exercise: replace x.^2 with x^2, and understand the cause of the error.) Exercise: Plot f (x ) = x 2 + 7x 6 on 1 x 8. Make it a black dotted line.

NRK (University of Minnesota)

MATLAB

2012.08.30

15 / 28

Function basics
Recall the quadratic formula: ax 2 + bx + c = 0 has the solutions b b 2 4ac x= 2a We will dene a function to solve the quadratic equation. It will take inputs a, b , c , and will output the results of the above formula.

NRK (University of Minnesota)

MATLAB

2012.08.30

16 / 28

Function basics
Recall the quadratic formula: ax 2 + bx + c = 0 has the solutions b b 2 4ac x= 2a We will dene a function to solve the quadratic equation. It will take inputs a, b , c , and will output the results of the above formula. How to do it: Go to File New Function Type in the following: function [positive,negative]=quadratic(a,b,c) %Solves a quadratic equation using the quadratic formula discriminant = b^2-4*a*c; positive = (-b + sqrt(discriminant))/(2*a); negative = (-b - sqrt(discriminant))/(2*a); end
NRK (University of Minnesota) MATLAB 2012.08.30 16 / 28

Function basics (cont.)


Save the le as quadratic.m The lename must match the function name. Close the editor window, and test your function on x 2 7x + 6 by typing [x1,x2]=quadratic(1,-7,6) Your answers should be x 1 = 6 and x 2 = 1.

NRK (University of Minnesota)

MATLAB

2012.08.30

17 / 28

Function basics (cont.)


Save the le as quadratic.m The lename must match the function name. Close the editor window, and test your function on x 2 7x + 6 by typing [x1,x2]=quadratic(1,-7,6) Your answers should be x 1 = 6 and x 2 = 1. Explanation: Line 1 tells MATLAB this function takes three inputs a,b,c and will output two values positive, negative. So, we fulll our promise to MATLAB by dening positive and negative within the function. The semicolons at the end of each line tell MATLAB to suppress output. Exercise: take them out to see what happens. MATLAB ignores anything after a % sign. Use this feature to write notes to yourself.
NRK (University of Minnesota) MATLAB 2012.08.30 17 / 28

Write Your Own Function

Exercise: Recall that the present value P of an annuity is P=R 1 (1 + i )n i

Where R is the payment per period, i is the interest rate per period, and n is the number of periods. Write a function called annuity_value to compute this.

NRK (University of Minnesota)

MATLAB

2012.08.30

18 / 28

Write Your Own Function

Exercise: Recall that the present value P of an annuity is P=R 1 (1 + i )n i

Where R is the payment per period, i is the interest rate per period, and n is the number of periods. Write a function called annuity_value to compute this. Check that your function works: A 10 year annuity at 5% annual interest with payments of $500 has a present value of $3860.87.

NRK (University of Minnesota)

MATLAB

2012.08.30

18 / 28

Anonymous Functions
Functions dont need to be saved to les. We can create them on the y, if needed. For example, nding the mean of the elements of a vector: we want to sum the elements, and divide by the length. Issue the command mean = @(x) sum(x)/length(x);

NRK (University of Minnesota)

MATLAB

2012.08.30

19 / 28

Anonymous Functions
Functions dont need to be saved to les. We can create them on the y, if needed. For example, nding the mean of the elements of a vector: we want to sum the elements, and divide by the length. Issue the command mean = @(x) sum(x)/length(x); mean = tells MATLAB to store the value (function, in this case) to the variable mean.

NRK (University of Minnesota)

MATLAB

2012.08.30

19 / 28

Anonymous Functions
Functions dont need to be saved to les. We can create them on the y, if needed. For example, nding the mean of the elements of a vector: we want to sum the elements, and divide by the length. Issue the command mean = @(x) sum(x)/length(x); mean = tells MATLAB to store the value (function, in this case) to the variable mean. @(x) indicates to MATLAB that you are dening a function which will take one argument called x.

NRK (University of Minnesota)

MATLAB

2012.08.30

19 / 28

Anonymous Functions
Functions dont need to be saved to les. We can create them on the y, if needed. For example, nding the mean of the elements of a vector: we want to sum the elements, and divide by the length. Issue the command mean = @(x) sum(x)/length(x); mean = tells MATLAB to store the value (function, in this case) to the variable mean. @(x) indicates to MATLAB that you are dening a function which will take one argument called x. sum(x)/length(x); tells MATLAB to take that x, calculate its sum and length, and divide them. Oh yeah... and suppress the output.

NRK (University of Minnesota)

MATLAB

2012.08.30

19 / 28

Anonymous Functions
Functions dont need to be saved to les. We can create them on the y, if needed. For example, nding the mean of the elements of a vector: we want to sum the elements, and divide by the length. Issue the command mean = @(x) sum(x)/length(x); mean = tells MATLAB to store the value (function, in this case) to the variable mean. @(x) indicates to MATLAB that you are dening a function which will take one argument called x. sum(x)/length(x); tells MATLAB to take that x, calculate its sum and length, and divide them. Oh yeah... and suppress the output. The whole expression @(x) sum(x)/length(x); actually is the function. It does not have a name until we assign it to mean.

NRK (University of Minnesota)

MATLAB

2012.08.30

19 / 28

Anonymous Functions (cont.)

Now try the command mean([2,4,6]). Did you get 4?

NRK (University of Minnesota)

MATLAB

2012.08.30

20 / 28

Anonymous Functions (cont.)

Now try the command mean([2,4,6]). Did you get 4? Try the command average = mean and use the newly named average function to calculate the average of some vector.

NRK (University of Minnesota)

MATLAB

2012.08.30

20 / 28

Anonymous Functions (cont.)

Now try the command mean([2,4,6]). Did you get 4? Try the command average = mean and use the newly named average function to calculate the average of some vector. Exercise: Write an anonymous function for present value of an annuity. It will take three arguments. P=R 1 (1 + i )n i

NRK (University of Minnesota)

MATLAB

2012.08.30

20 / 28

Working with Excel

Download http://www.math.umn.edu/~kirc0076/Orientation.xls This le is stock price data from Exxon and Chevron from 2009-2011 obtained from Yahoo! Finance.

NRK (University of Minnesota)

MATLAB

2012.08.30

21 / 28

Working with Excel

Download http://www.math.umn.edu/~kirc0076/Orientation.xls This le is stock price data from Exxon and Chevron from 2009-2011 obtained from Yahoo! Finance. In MATLAB, type [num,txt,raw] = xlsread(Z:\Orientation.xls) (Replace the pathname with whereever you put yours). Scroll up to see what num, txt, and raw are.

NRK (University of Minnesota)

MATLAB

2012.08.30

21 / 28

Plotting the Data

We are going to plot this data and determine the correlation coecient between the two stocks. Hypothesis: Since Exxon and Chevron are in the same business (oil), the correlation coecient will be positive (i.e. a Chevron gain will correspond with an Exxon gain since theyre both subject to the whims of the oil market). Since num holds the stock prices, create vectors of them with >> exxon = num(:,1) >> chevron = num(:,2) Now, plot with plot(exxon,chevron,s).

NRK (University of Minnesota)

MATLAB

2012.08.30

22 / 28

Scripts
For the correlation coecient, well write a script. A script is a function with no input or output. Recall that the correlation coecient is given by = where Cov (X , Y ) = (Xi X )(Yi Y ) , n Var (X ) = Cov (X , X ) Cov (X , Y ) Var (X )Var (Y )

Go to File New Script. Type the text on the following slide.

NRK (University of Minnesota)

MATLAB

2012.08.30

23 / 28

Our script
%Import exxon, chevron data from Excel [num,txt,raw]=xlsread(Z:\Orientation.xls); exxon = num(:,1); chevron = num(:,2); %Define anonymous functions for mean, variance, covariance mean = @(x) sum(x)/length(x); cov = @(x,y) sum((x-mean(x)).*(y-mean(y)))/length(x); var = @(x) cov(x,x); %Compute Correlation coefficient correl = cov(exxon,chevron)/sqrt(var(exxon)*var(chevron)); correl

NRK (University of Minnesota)

MATLAB

2012.08.30

24 / 28

Running the script

Save the le as correl.m Type correl in the Command Window MATLAB will execute each of the commands in that script. It will suppress output (note the semicolons). There is no semicolon on the last line. Therefore MATLAB prints the output for that line. I got .7966. Note the comments we typed. When we go back to this script, well have no trouble guring out whats going on.

NRK (University of Minnesota)

MATLAB

2012.08.30

25 / 28

Final Exercise

The best t line to a scatter plot has slope m= Cov (X , Y ) Var (X )

and intercept b = Y mX . Write a script to determine these quantities if X represents Exxon and Y represents Chevron.

NRK (University of Minnesota)

MATLAB

2012.08.30

26 / 28

Import Yahoo! Finance Data to Excel

The ticker symbol for Exxon is XOM, so go to http://finance.yahoo.com/q/hp?s=XOM+Historical+Prices. At the bottom of the screen, click the Download to Spreadsheet link.

NRK (University of Minnesota)

MATLAB

2012.08.30

27 / 28

Import Yahoo! Finance Data to MATLAB

Download http://math.umn.edu/~dodso013/fm503/0910/docs/ MATLAB/yahoo_prices.m and put it in your MATLAB path. The MATLAB command exxon=yahoo_prices({XOM},01-Jan-2009,31-Dec-2011); will grab Exxon stock price data from January 1, 2009 until December 31, 2011. It will get stored in the variable exxon.

NRK (University of Minnesota)

MATLAB

2012.08.30

28 / 28

Potrebbero piacerti anche