%% Robert Karol
% CDS 110a
% MATLAB Review
% Fall 2011
%%
%{
MATLAB Interface
- Current Directory
-> Lists the directory you will be running the program out of.
- Workspace
-> Holds a list of all currently defined variables.
- Command Window
-> Used for calling functions one at a time.
- Command History
-> Lists all previous functions which have been called.
- Editor
-> Write Scripts and Functions for calling multiple times.
- Changing Desktop Layout
-> Manually through clicking and dragging
-> Menu -> Desktop -> Desktop Layout -> Default
About MATLAB
- MATLAB stands for Matrix Laboratory
- Useful for quickly implementing numerical algorithms
- Vast array of built in numerical functions
- Easy to use visualization tools
- Basic data elements are mathematically expressive
- Interpreted Language
This tutorial has been written in the MATLAB Editor, and saved as a .m
file. You can take this file and open it in MATLAB and run it to review any
parts which you may have forgotten. All results will show up in the Command
Window.
%}
%% Getting Help
%{
Type help in the command window to get basic help.
Help followed by the function name gives details on how to use a given
function.
In all help files, the initial function name is given in all capital
letters. However, commands are executed using all lowercase letters.
You should follow this convention in all functions you write.
For example,
help ode45
The help file will list the function name, including all possible input and
output variables.
for more detailed help including example uses, try
doc ode45
%}
help ode45
%% Using the MATLAB Editor
% Use % to start a single line comment. All comments are colored green.
a = 1; % Can also comment after a line of code.
%{
Wrap multiline comments with
%{ and %}
Every block can be collapsed by clicking on the - sign at the start of
the block.
Do not write on the starting or ending lines of the block.
%}
%{
MATLAB Scripts vs Functions
Scripts
- Used to run a large number of functions in order.
- It saves the commands you have used for debugging in case some need to be modified slightly.
- This file is a script
Functions
- Can be called from any other function or script as long as it is in
the "Path"
- Must be written in a seperate .m file
- name of the .m file must match the name of the function
- Typically defined as follows
output = function my_function(variable1, variable2, variable3)
run the function here
end
Path
- The list of directories which MATLAB looks through to find functions.
- Your current directory is always on the Path.
%}
%{
MATLAB Color Scheme
Black -> Standard function call
Purple -> Defined variables
Green -> Comment
Blue -> Reserved Keyword, cannot be used as a variable name
- Function
- End
- If
Red -> Error Message
Orange -> Warning showing unused variables or unoptimized code.
Basic Cleanup Functions
Clc -> Clears the command window.
Clear All -> Clears all variables from your workspace.
Close All -> Closes all figures which have been created.
You may want to run each of these at the beginning of any script you
write to avoid variable name conflicts and potential mismatch errors.
When you see a %% at the start of a line, it creates a new "Cell". This
can be used to divide a script in the editor into multiple chunks so
that the entire file does not have to be run each time.
Ctrl + Enter evaluates the current cell.
Ctrl + Shift + Enter evaluates the current cell and advances the cursor
to the next cell.
Ctrl + Up and Ctrl + Down jumps between cells.
MATLAB has alternative definions for the word Cell but for now I will
use it to mean the seperate chunks of a script within the editor.
%}
%{
Types of MATLAB files
Program files: .m
Automatic backups: .~m or .asv
MATLAB figures (with data): .fig
MATLAB worksheet data: .mat
Exported figures: .eps, .png, etc.
%}
%% Basic data structures and operations.
2 + 6 % Will output the result 8
2 + 6; % Adding a semicolon supresses the output, but will save the ouput.
% Can be used to display the result of a calculation where you supressed
% the output.
disp('Current answer')
disp(ans)
% Whitespace is always ignored however I recommend sticking with a single
% convention as it will make your code easier to read.
3 - 2+ 1
% A nicer way to output data is to use the disp command.
disp('3 + 2 = ')
disp(3+2)
% Similar to just leaving off the semicolon but does not display the array name.
% Allows the user to quickly identify which lines are going to be
% displayed, and forces the writter to think about exactly what they want
% displayed.
% MATLAB follows order of operations
disp((6 + 3)/3)
disp((6 + 3/3))
% Changing the format of the output
format long
disp('Long Format')
disp(5/7)
format short
disp('Short Format'); disp(5/7); % Multiple commands per line separated by;
% Scientific format also works.
1.743e5
4.23e-2
%% Declaring and using Variables
% Variables in MATLAB do not need to be declared as in many computer
% languages. It can distinguish integers, floats, and strings.
% MATLAB is case sensitive.
a = 9
A = 1/3
b = 'Hello'
% Exponentiation
a^A
exp(a) % e^a
log(100) % uses natural log
log10(100) % log base 10
% Trig
% - Pi is defined internally in matlab.
pi
sin(pi) % Uses radians
sind(pi) % Uses degrees
cos(pi)
cosd(90)
% Imaginary numbers
exp(3.1415926i)
exp(3.1415926j)
real(exp(3.1415926j))
imag(exp(3.1415926j))
who % Lists all of the current variables which have been defined
clear A a;
who
clear all;
%% Arrays
% Matricies
w = [1, 2, 3] % row vector. Commas can separate elements.
x = [1 2 3] % row vector. Spaces can separate elements.
y = [1; 2; 3] % column vector. Colons separate rows.
z = [1
2
3] % Newlines also separate rows.
a = [1 2 3; 4 5 6; 7 8 9] % 3 by 3 matrix.
b = 1:10 % Colon means to increment. (default by 1)
c = 1:2:10 % Middle element is increment spacing.
d = [10:-1:1] % Brackets are optional.
e = linspace(1,6,25) % Generates a vector with 25 elements equally spaced between 1 and 6 inclusive.
%% Matrix Operations
A = 1:9
% Reshape command used to change dimensions of the matrix.
A = reshape(A,3,3)
B = 9:-1:1
B = reshape(B,3,3)
A + B % Matricies must be the same size, to be added
A + 3 % Adding a scalar to a matrix adds it at ever element.
A - B % Subtraction works as addition. Same size or scalar.
A * B % Works as matrix multiplication number of columns of A must match
% the number of rows of B.
A .* B % Elementwise Multiplication, every element of A is multiplied by the
% corresponding element in B.
A / B % Slash or matrix right division. B/A is roughly the same as
% B*inv(A). More precisely, B/A = (A'\B')'
A ./ B % A(i,j)/B(i,j) Same size or scalar
A \ B % A\B is roughly the same as inv(A)*B
A .\ B % B(i,j)/A(i,j)
3 ^ B % Matrix Exponentiation
A .^ B % A(i,j) to the B(i,j)
A = [i 0; 1+i, 2-i]
% Thes two are equivalent for real matricies.
A' % Complex conjugate transpose
A.' % Array transpose
%% Array initialization
A = ones(5,4)
A = zeros(3)
A = diag([1 2 3 4 5 6 7])
% The first index of a vector in MATLAB is 1, unlike most computer
% languages where the first element is indexed at 0.
x = A(1,:) % Extract the first row, with all columns
y = A(:,3) %
a = A(1:3,:)
b = A(1:2:5, 2:3:7) % 1,3,5 rows and 2, 5 columns
x(1)
y(end)
%% Data structures and operations: arrays
% Create random arrays.
A = randn(2,2)
B = rand(2,3)
% Concatenate matricies horizontally.
C = [A B]
C(1,:) = [] % Erase row 1
C(2,:) = C(1,:) % Place row 1 into row 2
C(1,:) = [1 2 3 4 5] % Replace row 1 with the numbers 1 - 5
dim = size(C) % Outputs the dimensions of C
C = C(:, [1 5 3 2 4]) % Permute columns
A = zeros(4,5) % Create a matrix of zeros
A = ones(4,5) % Create a matrix of ones
sum(A) % Sum along columns
sum(A,2) % Sum along rows
sum(sum(A)) % Sum all elements
%% More detailed array operation examples.
a = [4,5,1] * 2 % scalar multiplication
a = [1,2,3] + [4,5,6] % vector addition
% Usual matrix multiplication
A = [1 2; 3 4] * [1 2 3; 4 5 6]
A = [1 1 1; 1 1 1; 1 1 2];
A ^ 3
A * A * A
% element-wise operations
A
A .* A
ones(3,3)./A
A.^3
exp(A)
exp(2)
% Advanced operations.
inv(A) % Takes the inverse of a matrix
ans*A
expm(A) % Performs the matrix exponential, exp(A) would be elementwise
det(A) % Determinant of A
eig(A) % Outputs the eigenvalues of A
% By specifying the number of outputs, sometimes you can get more
% information out, for example in this case the same command eig gives the
% eigenvectors in the matrix V and values in the matrix D
[V D]=eig(A)
V*D-A*V
% search
A = [1 2 3 4 5]
idx = find(A >= 3)
A(idx) = A(idx) + 1
idx = find(isprime(A))
%% Strings
string = 'CDS 1 '
where = length(string)
temp = num2str(10)
% Similar to [ ] for matricies, but concatenates strings.
% however it ignores final spaces.
newstring_strcat = strcat(string, temp)
% [ ] can also be used for concatenation.
newstring_bracket = [string, temp]
%% Inf, NaN, and rounding
a = Inf % Infinity
1/a % 1/infinity = 0
a = NaN % Not a number
1/a
isnan(a) % returns 1 if a is not a number
f = 1.234;
% Round
f_round = round(f)
f_floor = floor(f)
f_ceil = ceil(f)
%% Anonymous functions
% Creates a function called my_function
% Takes an input x, adds one, and squares it.
my_function = @(x) (x+1).*(x+1);
my_function
my_function(2)
my_function(3)
my_function(4)
% The anonymous function is useful because it can be defined within a
% script or function and used as many times as needed.
% Anonymous functions can also be called within other functions. The quad
% function integrates the input function from a to b.
quad(my_function, 0, 1)
%% Flow Control with for loops
% Try to avoid using for loops and while loops. They are very inefficient
% in MATLAB.
% Factorial
n = 5;
temp = n;
for i = n-1:-1:1
temp = temp*i;
end
disp(temp);
% Initializing vectors
% Fibonacci Sequence
fibonacci = zeros(1,20); % Preallocation of vector for efficiency
fibonacci(1) = 1;
fibonacci(2) = 1;
for i = 3:20
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2);
end
disp(fibonacci);
% Initializing a matrix with nested for loops
A = zeros(3,3); % Preallocation
for i = 1:3
for j = 1:3
A(i,j) = i+j;
end
end
A
%% Flow control while loops and break statements
a = 10;
while a > 0;
disp(a)
a = a - 1;
if a == 3
break; % Breaks out of the innermost loop.
end
end
% No, a-- or a++
%% Flow control if, else, elseif statements and logical operators
round = rand(1)*2;
% AND &&, OR ||, NOT ~, LESS THAN <, GREATER THAN >, EQUAL TO ==
if a == 1;
disp('Equal to')
elseif a > 1;
disp('Greater than')
else
disp('Less than')
end
%% Example showing the advantage of vectorization.
% Use tic and toc to time commands, tic starts the timer, toc ends it.
% Matrix multiplication
A = 1:10000;
B = 10000:-1:1;
A = reshape(A,100,100);
B = reshape(B,100,100);
% For loop matrix multiplication
tic
for i=1:100
for j=1:100
C(i,j)=0;
for k=1:100
C(i,j)=C(i,j)+A(i,k)*B(k,j);
end
end
end
disp('Time with for loop method')
toc
% MATLAB matrix multiplication
tic
D = A*B;
disp('Time with MATLAB method')
toc
sum(sum(C == D))
%% Plotting
% Function plot - uses anonymous functions or .m functions as inputs
f = @(x) x.^2-x.^3; % Defines anonymous function f
close all % Closes the figure windows
fplot(f,0:2) % Function Plot
% Vector plot - most common
pause % Waits for the user to click a button before continuing
x = -1:.05:1;
plot(x,x.^2) % Overwrites previous plot
% Changing colors, line styles, and plotting multiple graphs on 1 axis
figure % Create new figure window
hold on % Keep everything plotted on the same axis
plot(x,2*x,'r')
plot(x,3*x,'r-')
plot(x,4*x,'o--')
plot(x,-2*x,'g.')
plot(x,-4*x,'k*')
plot(x,-8*x,'y')
% Labeling commands
title('This is a title','FontSize',16)
xlabel('x')
ylabel('y')
legend('red','red dashed', 'orange','green','black','\pi');
% Matlab accepts Latex input as well
figure
% Other interesting plotting functions
ezpolar('1+cos(2*t)')
figure
scatter(x,x.^3)
% There are also commands you can use for 3D plotting, histograms, bar
% plots saving figures, and numerous other plotting commands including
% animation functions. Use lookfor and help if you are interested.
%% ODE 45 - First Order Equations
% Define the anonymous function y' = f(t,y)
% In this case y' = 1/t^2(y^2+3*t)
yp =@(t,y) 1/t.^2.*(y.^2+3*t);
[t,y] = ode45(yp,[1,10],2); % Solve the ODE yp from time 1 to 10, using y'(t0)=2.
[t,y] % Display vectors.
plot(t,y) % Plot ODE solution.
%% ODE 45 - Second Order Equations
% Solving the second order differential equation
% y'' + p(t) y' + q(t) y = g(t) with y(t0) = 0, y'(t0) = 1
% Break it up into two first order ODE's
% x1' = x2
% x2' = -q(t) x1 - p(t) x2 + g(t) with x1(t0) = 0, x2(t0) = 1
% Choosing q(t) = t, p(t) = -e^t, g(t) = 3*sin(2*t) gives
% x1' = x2
% x2' = -t x1 + exp(t)*x2 + 3*sin(2*t) with x1(t0) = 0, x2(t0) = 1
% Now to create a function called secondode - See seperate .m file.
% Solve ODE
[t,x] = ode45('secondode',[0 1],[-3 1]); % Note ' around function name as it is in a seperate .m file.
% Also remember the .m file must be on MATLAB's Path
% Since x(1) = y, which is what we want to plot use the following function
plot(t,x(:,1))
xlabel('Time')
ylabel('y');
title('Y(t)')
%% Extra help if you get stuck
% Command Line
% - help fft -> gives basic usage help
% - doc fft -> hows examples of how to use the function
% - lookfor fft -> searches for functions which perform the operation.