matlab tutorial - math.umn.edu · pdf file• we will need some files later in this...
TRANSCRIPT
Matlab Tutorial
Fanda Yang
University of Minnesota
8/31/2017
File download
• We will need some files later in this tutorial. Please download them here:
http://z.umn.edu/mfm17-matlab
• Save those files into your Matlab working folder if you know what it is. Otherwise, save them to a new folder.
Click
Matlab first impression
• Open Matlab
• Type in “hello”
What we do today?
• Let’s play Sudoku– Matlab basics
– On-screen presentation
• OMG! It’s Linear Algebra– Special matrices
– Read data from Excel spreadsheet
• Hey Matlab, take the derivative for me– M-files
– Anonymous function
– 2D Graphing
• Advanced Topic– Logical values
– fminsearch
LET’S PLAY SUDOKU
Sudoku
8 6
3
2
• Use integers from 1 to 9 to fill out the matrix on the left
• Each row and column sum up to 15
• major diagonal and minor diagonal sum up to 15 too
Sudoku
8 1 6
3 5 7
4 9 2
• magic(3)
Variable declaration
• Claim a variable like you claim shotgun seat– Don’t worry about data type
– Case sensitive
• a = 2
• b = 2^2
Matrix and vector definition
• A matrix is an array of vectors– A 4 by 3 matrix can be viewed as 4 row vectors or 3 column vectors
•
1 4 98 3 54 7 39 4 0
•
− 𝒓𝟏 −− 𝒓𝟐 −− 𝒓𝟑 −− 𝒓𝟒 −
•
| | |𝒄𝟏 𝒄𝟐 𝒄𝟑| | |
• Comma separates Columns; semicolon separates rows
Syntax (row vector)• r1 = [1,4,9]• r2 = [8 3 5]
• r3 = [4 7 3]• r4 = [9 4 0]
Syntax (column vector)• c1 = [1;8;4;9]• c2 = [4;3;7;4]• c3 = [9;5;3;0]
Syntax (matrix)• X = [1 4 9; 8,3,5; 4,7,3; 9 4 0]• X = [r1;r2;r3;r4]• X = [c1,c2,c3]
Exercise
• Define this matrix on your computer1 2 34 0 00 0 6
Heuristic Discussion: how do WE know it’s right?
8 1 6
3 5 7
4 9 2
• Let’s write a small program to verify this answer
• A = magic(3)
WE
A
Heuristic Discussion: how do WE know it’s right?WE
8 1 61. Grab a row out of the matrix
2. Sum up the 3 numbers in the row
3. Check if the sum is 15
Search for how to take sum of an array in matlab
http://www.bing.com
Bing it on!You can google it too if you want.
Heuristic Discussion: how do WE know it’s right?WE
8 1 61. Grab a row out of the matrix
8 1 6sum( ) 2. Sum up the 3 numbers in the row
3. Check if the sum is 158 1 6sum( ) == 15
Heuristic Discussion: how do WE know it’s right?WE
A(1,:)1. Grab a row out of the matrix
A(1,:)sum( ) 2. Sum up the 3 numbers in the row
3. Check if the sum is 15A(1,:)sum( ) == 15
Matrix indexing
• A(i,j) entry at ith row & jth column
• A(i,:) ith row
• A(:,j) jth column
• A(i1:i2,j) rows from i1 to i2 intersect with jth column
• The trick of Boolean / logical indices– Example
• A(A<5)=0
– The above code replaces entries that are smaller than 5 in A with 0
• For more information about matrix indexing– http://www.mathworks.com/help/matlab/math/matrix-indexing.html
Matrix indexing - Caveat
• Matlab does not support A(i,:)(j). This won’t give you the (i,j) entry.
• What you can do is to split up the expression into two lines:– r1 = A(1,:);
– r1(2)
Operators & Equivalent
• Arithmetic– +, -, ^ (power), ’ (transpose), *, /• Inverse: A^-1 or inv(A)
• Transpose alternative: transpose(A)
– dot operators: .*, ./, .^. More on this later
• Relational – <, <=, >, >=, ==, ~= (not equal to)
• Logical– & (logic AND), | (logic OR), ~ (logic NOT), xor (logic XOR)
– any(), all()
• For more information– http://www.mathworks.com/help/matlab/operators-and-elementary-
operations.html
Exercise: how do we check columns all at once?
8 1 6
3 5 7
4 9 2
• all(sum(A,1)==15)
• Also, verify – all rows
– the (major) diagonal
Exercise: how do we check minor diagonal?
8 1 6
3 5 7
4 9 2
• Hint: Use the following functions
• fliplr: flips left to right
• diag: gets diagonal entries of a matrix or forms a diagonal matrix from a vector
Data management (Workspace variables)
• save (filename [, variables])– Saves workspace variables to a file
– filename: name of the file to be saved. File extension “.mat”. Use single quotation marks to enclose the file name.
– variables: a list of variable to be saved. Use quotation marks to enclose each variable name.
• load filename– Loads workspace variables from a .mat file
– filename: name of the file to be saved. File extension “.mat”. Use single quotation marks to enclose the file name.
Present results NICELY
• disp(X)– Display matrix X on screen without printing matrix name
• fprintf(format [, var_list])– Write formatted variable values on screen. C++ style
– format is a string type parameter. You can print literal text together with conversion specifications. You always want to end this parameter with “\n”
– var_list is a list of variables whose values will be printed on screen.
– Examples:
• fprintf('The value of Pi is %.8f.\n',pi)
• fprintf('%d\t%d\t%d\n',A’)
– For more information:• http://www.mathworks.com/help/matlab/ref/fprintf.html#inputarg_formatSpec
Exercise: Display a matrix
• Display matrix B=
11.9 12.345 13.321 22 2331 32 3341 42 43
as shown below:
– matrix B can be loaded from “data.mat”
Display in fixed-point:11.900000 12.345000 13.30000021.000000 22.000000 23.00000031.000000 32.000000 33.00000041.000000 42.000000 43.000000
Display in 2 decimal places:11.90 12.35 13.3021.00 22.00 23.0031.00 32.00 33.0041.00 42.00 43.00
Exercise: Display a matrix
• Display matrix B=
11.9 12.345 13.321 22 2331 32 3341 42 43
as shown below:
– matrix B can be loaded from “data.mat”
Display in exponential notation:1.190000e+01 1.234500e+01 1.330000e+012.100000e+01 2.200000e+01 2.300000e+013.100000e+01 3.200000e+01 3.300000e+014.100000e+01 4.200000e+01 4.300000e+01
Display in exponential notation with 2 decimal places:1.19e+01 1.23e+01 1.33e+012.10e+01 2.20e+01 2.30e+013.10e+01 3.20e+01 3.30e+014.10e+01 4.20e+01 4.30e+01
OMG! IT’S LINEAR ALGEBRA
Nah~ You will be fine
Special Matrices
• Try on your computer and see what they do
• zeros(m,n)– If m=n, the syntax can be simplified as zeros(m)
• ones(m,n)
• eye(n)
• eye(m,n)
creates an m by n zero matrix
forms an m by n matrix of 1’s
creates an n by n identity matrix
generates an m by n zero matrix then fills the major diagonal with 1’s
Handy linear algebra tricks
• Switch rows– I3 = eye(3);
– C = [I3(2,:);I3(1,:);I3(3,:)]
• Switch column 1 and 2– A = magic(3)
– A * C
• Switch row 1 and 2– C * A
Handy linear algebra tricks
• Column sums – ones(1,3) * A
– 1 1 1 ×8 1 63 5 74 9 2
= [15 15 15]
– same as sum(magic(3),1)
• Row sums– Anyone?
Handy linear algebra tricks
• Column average– Anyone?
• Row average
Load data from Excel
• Before you guess, let’s load some data from Excel.
• Syntax:– X = xlsread(file_name [, sheet_name, range])
– file_name: the file name of the Excel spreadsheet
– sheet_name: optional, name of the sheet, a.k.a. tab name of the spreadsheet
– range: optional, data range in the sheet. ie: A3:D8
• In Matlab type in:
– The first line empties Matlab memory (Workspace). The second line reads data from available range of Sheet2 in book1.xlsx and returns a variable called “data”.
clear;
data = xlsread('book1.xlsx','Sheet2');
Guess what we are doing here
• Keep typing:
– You may copy-paste the chuck if you have the pdf version.
• Now guess what this line is doing here:
X = data(:,1:2); %extract first 2 columns into X
Y = data(:,end); %grab the last column
clear data; %destroy variable data
X = [X, ones(size(X,1),1)]; %add a column of 1’s to the
end of X
b = (X'*X)^-1*X'*Y
Guess what we are doing here
• Plot the curve in 2DZ = (1:.1:10)';
Z = [Z, Z.^2, ones(size(Z,1),1)];
Y_hat = Z*b;
plot(Z(:,1), Y_hat,'LineWidth',3);
set(gca,'Fontsize',14);
HEY MATLAB, TAKE THE DERIVATIVE FOR ME
Here’s the problem
• Take the derivative of the following function and evaluate at
𝑥 = 3,2,1
3𝑝𝑖.
𝑓 𝑥 = 𝑥5 + log𝑠𝑖𝑛 𝑥
𝑡𝑎𝑛 𝑥+ 𝑒
𝑥2
2
• Plot the function
Two types of M-files
• Script– Has no input or output arguments
– Stores a sequence of commands to be used repeatedly in future
• Function– May accept input or output arguments
– File name has to be the same as the function name defined inside
• To create an M-file, just type in
• edit file_name
Exercise: Create a script m-file
• Create an m-file named fstscript
• edit fstscript
Anonymous function
• Anonymous function is not stored in a program file and usually is treated like a variable. It accepts inputs and returns outputs.
• Syntax:– function_name = @(input_list) expression
– input_list: list of input arguments separated by colons
– function_name: the name of the function. It is actually a function handle.
• To save some debug time, avoid putting already defined variables into input_list.
x = 5;
myfx = @(x) x^2;
myfx(7)
Exercise: Define the function as anonymous function in m-file
• Take the derivative of the following function and evaluate at
𝑥 = 3,2,1
3𝑝𝑖.
𝑓 𝑥 = 𝑥5 + log𝑠𝑖𝑛 𝑥
𝑡𝑎𝑛 𝑥+ 𝑒
𝑥2
2
• Plot the function
Vectorization
• Our anonymous function probably can only process one number at a time. How about a vector of numbers?
• Prove? – vecX = [3 2 pi/3]
– myfx(vecX)
• Use dot operator to vectorize our function:– Dot operator is a cell-by-cell operator that works best for vectors
– Replace
• ^ to .^
• / to ./
– Most Matlab built-in functions are already vectorized: log, exp, sin, tan…
The derivative
• Simple notion (Differentiation):
– 1𝑠𝑡 𝑑𝑒𝑟𝑖𝑣𝑎𝑡𝑖𝑣𝑒 =𝑐ℎ𝑎𝑛𝑔 𝑖𝑛 𝑓
𝑐ℎ𝑎𝑛𝑔𝑒 𝑖𝑛 𝑥=
Δ𝑓
Δ𝑥=
f x+Δx −f(x)
Δ𝑥
• Definition:
– 𝑓′ 𝑥 = limℎ→0
𝑓 𝑥+ℎ −𝑓(𝑥)
ℎ
• Numerical differentiation
– 𝑓′ 𝑥 ≈𝑓 𝑥+𝑚 −𝑓(𝑥−𝑚)
2𝑚
– 𝑚 is a very small number, like 0.001
– 𝑥 is the value at which 𝑓′ is evaluated
Function in an m-file
• Create an m-file named “mydev”
• Define function mydev as the following:function [rtn] = mydev(func, eval)
end
• The above code defined a function named “mydev”
• The function takes two input arguments: “func” and “eval”
• It also returns to an output argument “rtn”
• “func” denotes any anonymous function with one input argument
• “eval” denotes the value at which the derivative is evaluated
Exercise: Define a function
• Implement the numerical differentiation equation
𝑓′ 𝑥 ≈𝑓 𝑥 +𝑚 − 𝑓(𝑥 − 𝑚)
2𝑚
• In mydev.m
Exercise: Implement the first bullet point
• Take the derivative of the following function and evaluate at
𝑥 = 3,2,1
3𝑝𝑖.
𝑓 𝑥 = 𝑥5 + log𝑠𝑖𝑛 𝑥
𝑡𝑎𝑛 𝑥+ 𝑒
𝑥2
2
• Plot the function
• In fstscript.m
2D plot
• In order to plot something, you need to create a series of points in Cartesian coordinate system (XY plane)
• The command to make any two-dimensional graph is plot.
• Syntax:– plot(X, Y, LineSpec)
– X: a vector of values on the X-axis
– Y: a vector of values on the Y-axis
– LineSpec: a string that specifies the appearance of the line. For detailed definition, see http://www.mathworks.com/help/matlab/ref/linespec.html.
Exercise: Plot 𝑓(𝑥) from 𝑥 = 0 to 1
• Take the derivative of the following function and evaluate at
𝑥 = 3,2,1
3𝑝𝑖.
𝑓 𝑥 = 𝑥5 + log𝑠𝑖𝑛 𝑥
𝑡𝑎𝑛 𝑥+ 𝑒
𝑥2
2
• Plot the function from 0 to 1
• In fstscript
ADVANCED TOPIC
Way to be a nerd
Logical values
• It’s all about 0 and 1– Logical TRUE is treated as 1 in computation
– Logical FLASE is treated as 0 in computation
• The expression 3>1 equals 1
• The expression 1>3 equals 0
• Why do I care?– Indexing matrices
– Defining piecewise function / if-statement alternative
A(A>5)=0;
Exercise: Make a vectorized piecewise function
• The absolute value function is defined as:
𝑓 𝑥 = ቊ−𝑥, 𝑥 < 0𝑥, 𝑥 ≥ 0
• How can we define a vectorized anonymous function that implements the absolute value function in one single line?
Condition Value of (x<0) Value of 𝑓 𝑥 Value of (x<0)*x
𝑥 < 0 1 −1 × 𝑥 x
𝑥 ≥ 0 0 1 × 𝑥 0
Condition Value of (x>=0) Value of 𝑓 𝑥 Value of (x>=0)*x
𝑥 < 0 0 −1 × 𝑥 0
𝑥 ≥ 0 1 1 × 𝑥 x
Exercise: Make a vectorized piecewise function
• The absolute value function is defined as:
𝑓 𝑥 = ቊ−𝑥, 𝑥 < 0𝑥, 𝑥 ≥ 0
• How can we define a vectorized anonymous function that implements the absolute value function in one single line?
• myabs = @(x) (x>=0) .* x - (x<0) .* x;
• myabs2 = @(x) (2*(x>=0)-1) .* x;
Function fminsearch
• The built-in function fminsearch performs an unconstrained search for a minimum value of a function
• Syntax:– [x, fval] = fminsearch(fun, x0)
– fun: function handle that links to a function with one input and one output. This function can be a built-in function, a user defined anonymous function or a function that’s defined in a function m-file. You usually put an “@” sign before function name to pass your function as function handle
– x0: initial guess
– x: the value at which the minimum value is found
– fval: optional, the minimum value that is found
Function fminsearch
• Example:– [x1 fmin1]= fminsearch(@(x) x^2 +3*x + 4, 1)
– Alternatively, we can write things in two lines:
– qufx = @(x) x^2 +3*x + 4;
– [x1 fmin1]= fminsearch(qufx , 1)
• Example 2: Least Square
– min𝒃
𝑆𝐸 = σ𝑖 𝑦𝑖 − ො𝑦𝑖2 = σ𝑖 𝑦𝑖 − 𝒙 ∙ 𝒃 2
– In Matlab, we can define SE as:
– sefx = @(b) sum((Y – X*b).^2);
– Now can you use fminsearch to find the b that minimizes sefx?
– Set x0 = [2;3;4]
Exercise: Numerical OLS
• Load the data as before
• Use fminsearch to solve the ordinary least square coefficient
clear;
data = xlsread('book1.xlsx','Sheet2');
X = data(:,1:2); %extract first 2 columns into X
Y = data(:,end); %grab the last column
clear data; %destroy variable data
X = [X, ones(size(X,1),1)]; %add a column of 1’s to the
end of X
M-files from today
• Code introduced in this tutorial can be downloaded at the following link:
– https://z.umn.edu/mfm17-matlab-full