When you start MATLAB, the desktop appears in its default layout. (R2015b)
Tabs -- open, edit, and save files, data, plots, etc.
Current Folder -- access your files
Command Window -- command line, indicated by the prompt >>
Workspace -- explore data that you create or import from files
The simplest interaction with the command window is to use it as a calculator.
The arithmetic symbols +, -, *, / and ^ have their usual meanings
5 + 7
ans = 12
Note the result above is stored in an object named ans. When you do not specify an output variable, MATLAB uses the variable ans to store the results of your calculation. You can also create an object with your chosen name to hold the result of your calculation.
my_result = 2^3+1
my_result = 9
my_string = 'HelloAPEC'
my_string = HelloAPEC
Note in your Workspace you can see the variables ans and my_result after you run the above commands. You can recall previous commands by pressing the up- and down-arrow keys.
Individual commands can be gathered together in an m-file and run together. To create an m-file, click HOME -> New -> Script. Once a new m-file window is open, you can start writing your commands line-by-line. Save your m-file using a meaningful name. You can run your entire m-file by clicking Run from the EDITOR tab, or you can test part of the codes by first selecting them then use right-click -> Evaluate Selection (or F9). MATLAB m-files can also be divided into sections with "%%", then you can also quickly run your current command section with Ctrl+Enter
When working in MATLAB, it is important to set up your current working directory so MATLAB knows where to look for files and where to save your data and file.
Type pwd at the command line to find out the current working directory
Type cd('C:\Users\Your Working Directory') to set your working directory
Begin with a letter
From the 2nd character onward: letters, digits, or underscores
No blanks/space or any special characters other than underscores allowed
Avoid conflicts with reserved names or functions (such as i, j, pi, log, char, size).
The unit imaginary number is preassigned to the varialbe i or j.
pi is also predefined in MATLAB.
In general, variable names take precedence over function names. If you create a variable that uses the name of a function, you sometimes get unexpected results. Check whether a proposed name is already in use with the exist function. exist returns 0 if there are no existing variables, functions, or other artifacts with the proposed name.exist returns other values depending on the various exisitance status. Type help exist for details. For example:
exist my_var_name
ans = 0
If you inadvertently create a variable with a name conflict, remove the variable from memory with the clear function.
MATLAB is an abbreviation for "matrix laboratory." MATLAB® is designed to operate primarily on whole matrices and arrays.
Vector
To create a row vector, separate the elements with either a comma (,) or a space.
a1 = [1, 2, 3, 4] % Or equivalently:% a1 = [1 2 3 4]
a1 = 1 2 3 4
To create a column vector, separate the elements with either a semicolon (;) or in separate rows.
a2 = [1; 2; 3; 4] % Or equivalently:% a2 = [1% 2% 3% 4]
a2 = 1 2 3 4
Strings
my_string = ['Hello, I am ', 'Yuan']
my_string = Hello, I am Yuan
The colon operator also allows you to create an equally spaced vector of values using the more general form start:step:end. If you omit the middle step, as in start:end, MATLAB uses the default step value of 1.
S = 0:10:100 S = 1:10 S = 10:-1:5
S = 0 10 20 30 40 50 60 70 80 90 100 S = 1 2 3 4 5 6 7 8 9 10 S = 10 9 8 7 6 5
Function linspace
linspace(0, 1, 5)
ans = 0 0.2500 0.5000 0.7500 1.0000
Function logspace(X1, X2, N)
logspace(1, 3, 3)
ans = 10 100 1000
Matrix
To create a matrix that has multiple rows, separate the rows with semicolons or in separate rows
b = [1, 1, 1; 4, 5, 6; 7, 8, 10] % Or equivalently:% b = [1 1 1% 4 5 6% 7 8 10]
b = 1 1 1 4 5 6 7 8 10
Another way to create a matrix is to use a function, such as ones, zeros, eye, or rand. For example, create a 3-by-1 column vector of zeros.
c0 = zeros(3, 1) c1 = eye(3)
c0 = 0 0 0 c1 = 1 0 0 0 1 0 0 0 1
Random number generation
rand(3) Xu = -5 + (5+5)*rand(4,2) %[-5,5] Xn = 3 + 2*randn(4,3) % N(3, 2)
ans = 0.8729 0.8666 0.8541 0.8447 0.9498 0.0987 0.5384 0.8264 0.6513 Xu = 2.0352 2.7024 1.1024 2.3173 2.9962 -2.4030 -4.6543 -2.4293 Xn = 3.9854 3.6417 5.6191 1.6983 5.8406 3.2307 4.8537 0.6201 8.6563 2.6238 1.1431 3.5482
Concatenation
Concatenation is the process of joining arrays to make larger ones.
Horizontal concatenation
B1 = [b, b]
B1 = 1 1 1 1 1 1 4 5 6 4 5 6 7 8 10 7 8 10
Vertical concatenation
B2 = [b; b]
B2 = 1 1 1 4 5 6 7 8 10 1 1 1 4 5 6 7 8 10
Creating a Block Diagonal Matrix.
B3 = blkdiag(b, b)
B3 = 1 1 1 0 0 0 4 5 6 0 0 0 7 8 10 0 0 0 0 0 0 1 1 1 0 0 0 4 5 6 0 0 0 7 8 10
Replicating a matrix
B4 = repmat(b, 2, 1)
B4 = 1 1 1 4 5 6 7 8 10 1 1 1 4 5 6 7 8 10
Vector-Scalar
v1 = [1, 2, 3] v1 * 2 v1 .^ 2
v1 = 1 2 3 ans = 2 4 6 ans = 1 4 9
Vector Addition and Subtraction
v1 + v1 v1 - v1
ans = 2 4 6 ans = 0 0 0
Vector Multiplication
v2 = v1' v1 * v2 % Inner product v2 * v1 % Outer product
v2 = 1 2 3 ans = 14 ans = 1 2 3 2 4 6 3 6 9
Vector-Matrix Multiplication
v1 * b % b * v1
ans = 30 35 43
MATLAB allows you to process all of the values in a matrix using a single arithmetic operator or function.
b+10
ans = 11 11 11 14 15 16 17 18 20
sin(b)
ans = 0.8415 0.8415 0.8415 -0.7568 -0.9589 -0.2794 0.6570 0.9894 -0.5440
To transpose a matrix, use a single quote ('):
b'
ans = 1 4 7 1 5 8 1 6 10
The * operator computes the standard matrix multiplications
b * b
ans = 12 14 17 66 77 94 109 127 155
The .* operator computes element-wise multipliation. Here the . signifies that the operation is to element by element
b .* b
ans = 1 1 1 16 25 36 49 64 100
Use function inv() to obtain the inverse of a matrix,
inv(b)
ans = 2.0000 -2.0000 1.0000 2.0000 3.0000 -2.0000 -3.0000 -1.0000 1.0000
Test that a matrix mulplied by its inverse is the identity matrix
p = b * inv(b)
p = 1.0000 0.0000 0 -0.0000 1.0000 0 -0.0000 0.0000 1.0000
Notice that p is not a matrix of integer values. MATLAB stores numbers as floating-point values, and arithmetic operations are sensitive to small differences between the actual value and its floating-point representation. You can display more decimal digits using the format command. Refer the following tables for the specific format styles.
b size(b) sum(b, 1) mean(b, 2) max(b, [], 1)
b = 1 1 1 4 5 6 7 8 10 ans = 3 3 ans = 12 14 17 ans = 1.0000 5.0000 8.3333 ans = 7 8 10
% * *Kronecker product*%% <<Kronecker.png>>% K1 = eye(2) K2 = [1, 2, 3; 4, 5, 6] K1K2 = kron(K1, K2) K2K1 = kron(K2, K1)
K1 = 1 0 0 1 K2 = 1 2 3 4 5 6 K1K2 = 1 2 3 0 0 0 4 5 6 0 0 0 0 0 0 1 2 3 0 0 0 4 5 6 K2K1 = 1 0 2 0 3 0 0 1 0 2 0 3 4 0 5 0 6 0 0 4 0 5 0 6
Use indexing when you want to access selected elements of an array.
Vector indexing
v = [16 5 9 4 2]
v = 16 5 9 4 2
Single value
v(3)
ans = 9
Multiple elements
v([1, 3, 5]) %index with a vector v(1:3) %colon operator v(end) %Special end operator v(3:end-1) v(1:2:end) % Extract all the odd elements v([1, 3]) = [0, 100]
ans = 16 9 2 ans = 16 5 9 ans = 2 ans = 9 4 ans = 16 9 2 v = 0 5 100 4 2
For example, consider the following 3-by-3 matrix A
A = [11, 21, 31; 41, 51, 61; 71, 81, 91]
A = 11 21 31 41 51 61 71 81 91
Most common way to refer to a particular element is to specify row and column subscripts using "( )" (not "[ ]"), such as
A(2, 3)
ans = 61
Less common, but sometimes useful, is to use a single subscript that traverses down each column in order:
A(8)
ans = 61
To refer to multiple elements of an array, use the colon operator, which allows you to specify a range of the form start:end. For example, list the elements in the first two rows and the second column of A:
A(1:2, 2) A([2,1], 2:end)
ans = 21 51 ans = 51 61 21 31
The colon alone, without start or end values, specifies all of the elements in that dimension. For example, select all the columns in the third row of A:
B = A(3, :)
B = 71 81 91
Logical indexing
find ( A > 50 & A < 80 ) (A > 50) & (A < 80) A( (A > 50) & (A < 80) ) = NaN isnan(A) A (~any(isnan(A),2), :) %Remove all rows with NaN value
ans = 3 5 8 ans = 0 0 0 0 1 1 1 0 0 A = 11 21 31 41 NaN NaN NaN 81 91 ans = 0 0 0 0 1 1 1 0 0 ans = 11 21 31
Here is an example of a m-file.
% vol_sphere.m% Adopted from J.C. Frain, 2014% This m-file calculates the volume of a sphere clc; % Clear the Command Window display clear all; % Clear Workspace (All variables will be removed from memory) format compact %Control line spacing format %Use "format loose" if you want extra blank lines%Main codes r = 2; % Assign radius value to r volume = (4/3) * pi * r^3; % Calculate volume%Display result result_string = ['The volume of a sphere of radius ' ... num2str(r) ' is ' num2str(volume)]; disp(result_string)
The volume of a sphere of radius 2 is 33.5103
Suppose we have the following model for prodicting wheat yield:
In this exercise, do the following:
Create fertilizer as a 100x1 column vector of normally distributed random numbers with mu=9 sigma=2
Create rainfall as a 100x1 column vector of normally distributed random numbers with mu=7 sigma=3
Create u as 100x1 colum vector of normally distributed random numbers with mu=0 sigma=1
Create WheatYield = 10 + 4 * fertilizer + 2 * rainfall + u
For dependent variable, assign y = WheatYield
For explanatory variables, assign X = [ones(100,1), fertilizer, rainfall]
Calculate the OLS estimation of b0, b1, b2 with b = (X'*X)\X'*y
Calculate the residuals e = y - X * b
Calculate the residual sum of squares SSR = e'*e
% Ex_Lec01_OLS.m% Exercise for 2016 APEC "Intro to Num Analysis Software" short course% Lecture 01 Ordinary Linear Regression example% Yuan Chai% 2016-08-01% Workspace setup clc; %clear command window clear; %clear workspace format compact % set display format as compact rng(1); %set random number seed% Model setup fertilizer = 9+2*randn(100,1); rainfall = 7+3*randn(100,1); u = randn(100,1); WheatYield = 10 + 4*fertilizer + 2*rainfall + u; % OLS y = WheatYield; %Dependent Variable X = [ones(100,1), fertilizer, rainfall]; % Explanatory Variable b = (X'*X)\(X'*y) %OLS beta estimation% Residuals e = y - X * b; SSR = e'*e
b = 10.1584 4.0031 1.9932 SSR = 77.4891