Getting started with MATLAB

advertisement
Getting started with MATLAB
You can work through this tutorial in the computer classes over the first 2 weeks, or in your own time.
The Farber and Goldfarb computer classrooms have working Matlab, but it can be downloaded with your
UNET id onto your laptop, as Brandeis has a site license. See:
https://sites.google.com/a/brandeis.edu/matlab/student-computers
and open the file within that page: “matlab_insructions.pdf”
Be sure to click “Academic Use” (not “Student Use”) when asked “How will you use the Matlab
software?”
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Introduction to Matlab
% This course is adapted from MIT, Stanford, U Delaware Matlab crash
% courses.
% I have used the documents written by Stefan Roth and Tobin Driscoll
% besides the Matlab online tutorial. Azadeh Samadani 01/10/2007
% Adapted more for BIOL135b and NBIO136b by Paul Miller 01/10/2009
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Useful links: The Getting Started with MATLAB manual is a very good place to get a more gentle and thorough
introduction:
http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/
http://www.mathworks.com/academia/student_center/tutorials/
Basics:
If you type in a valid expression and press Enter, MATLAB will immediately execute it and return the result, just
like a calculator.
>> 2+2
ans =
4
>> 4ˆ2
ans =
16
>> 1/0
Warning: Divide by zero.
ans =
Inf
Notice the special expression here: Inf for ∞. Another special value is NaN, which stands for not a number. NaN is
used to express an undefined value. For example,
>> Inf/Inf
ans = NaN
* Challenge: Calculate the following statements: !
= 1+ 5
2
.
Here are a few other demonstration statements.
%
% Anything after a % sign is a comment.
x = rand(2,2);
% ; means "don’t print out result"
s = ’Hello world’;
% single quotes enclose a string
t = 1 + 2 + 3 + ...
4 + 5 + 6 % ...
% ... means continue a line
Here are a few useful commands:
who
cd
pwd
dir
ls
%
%
%
%
%
gives you your variables
Change current working directory.
Show (print) current working directory.
List directory.
List directory.
A = [1 2; 3 4];
B = [1,2; 3,4];
%
%
%
%
%
Creates a 2x2 matrix
The simplest way to create a matrix is
to list its entries in square brackets.
The ";" symbol separates rows;
the (optional) "," separates columns.
N
v
v
v
%
%
%
%
%
%
%
%
%
A scalar
A row vector
A column vector
Transpose a vector (row to column or
column to row)
A vector filled in a specified range:
[start:stepsize:end], brackets are
optional
Empty vector
* Type why in your command window
Creating matrices and vectors
=
=
=
=
5
[1 0 0]
[1; 2; 3]
v'
v = 1:0.5:3
v = pi*[-4:4]/4
v = []
Creating special matrices
1ST parameter is ROWS, 2ND parameter is COLS
m
v
m
v
=
=
=
=
zeros(2, 3)
ones(1, 3)
eye(3)
rand(3, 1)
m = zeros(3)
%
%
%
%
%
%
Creates a 2x3 matrix of zeros
Creates a 1x3 matrix (row vector)of ones
Identity matrix (3x3)
Randomly filled 3x1 matrix (column
vector); see also randn
Creates a 3x3 matrix (!) of zeros
* Challenge: Create a 3x1 matrix with random elements between 0 and 5. (Hint: >>doc rand)
•
Challenge: Find the row-wise sum of the elements of A. Find the column-wise product of the elements of
A. (Hint: >>doc sum)
Indexing vectors and matrices
% Warning: Indices always start at 1 and *NOT* at 0!
v = [1 2 3];
v(3)
% Access a vector element
m = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
m(1, 3)
% Access a matrix element
% matrix(ROW #, COLUMN #)
m(2, :)
% Access a whole matrix row (2nd row)
m(:, 1)
% Access a whole matrix column(1st column)
m(1, 1:3)
% Access elements 1 through 3 of the 1st
% row
m(2:3, 2)
% Access elements 2 through 3 of the
% 2nd column
m(2:end, 3)
% Keyword "end" accesses the remainder of
% a column or row
m = [1 2 3; 4 5 6]
size(m)
% Returns the size of a matrix
size(m, 1)
% Number of rows
size(m, 2)
% Number of columns
m1 = zeros(size(m))
% Create a new matrix with the size of m
*Challenge: Create a 5x3 matrix with random elements and access the (3x2) elements on the lower right hand
corner. (Hint: >>help end)
Remember to check the help system often! It is really easy! If you know the command that you want to obtain some
info about it is as easy as typing help command where command is the command that you are interested in.
Simple operations and the “dot” modifier
a
2
a
b
a
a
a
a
= [1 2 3 4]';
* a
/ 4
= [5 6 7 8]';
+ b
- b
.^ 2
.* b
a ./ b
%
%
%
%
%
%
%
%
%
%
A column vector
Scalar multiplication
Scalar division
Another column vector
Vector addition
Vector subtraction
Element-wise squaring (note the ".")
Element-wise multiplication (note the
".")
Element-wise division (note the ".")
* Challenge: Define two arbitrary vectors A and B with same dimensions. Calculate A*B, A.*B and A*B’? What is
the answer to A/B and A./B? Which operations do not make sense?
Vector operations
% Built-in Matlab functions that operate on vectors
sum(a)
mean(a)
std(a)
max(a)
min(a)
%
%
%
%
%
Sum of vector elements
Mean of vector elements
Standard deviation
Maximum
Minimum
* Challenge: Without using a for loop, calculate the sum of all prime numbers less than 100. (Hint:>>help
isprime)
% If a matrix is given, then these functions will operate on each column of
the matrix and return a row vector as result
a = [1 2 3; 4 5 6]
mean(a)
max(a)
max(max(a))
%
%
%
%
A matrix
Mean of each column
Max of each column
Obtaining the max of a matrix
x = [0 1 2 3 4];
plot(x);
pause
plot(x, 2*x);
axis([0 4 0 8]);
%
%
%
%
%
Basic plotting
Plot x versus its index values
Wait for key press
Plot 2*x versus x
Adjust visible rectangle
figure;
x = pi*[-24:24]/24;
plot(x, sin(x));
xlabel('radians');
ylabel('sin value');
title('dummy');
% Open new figure
Graphics (2D plotting)
figure;
subplot(1, 2, 1);
plot(x, sin(x));
axis square;
subplot(1, 2, 2);
plot(x, 2*cos(x));
axis square;
figure;
plot(x, sin(x));
hold on;
plot(x, 2*cos(x), '--');
legend('sin', 'cos');
hold off;
figure;
m = rand(64,64);
imagesc(m)
%colormap gray;
axis image;
axis off;
% Assign label for x-axis
% Assign label for y-axis
% Assign plot title
% Multiple functions in separate graphs
% (see "help subplot")
% Make visible area square
%
%
%
%
%
Multiple functions in single graph
'--' chooses different line pattern
Assigns names to each plot
Stop putting multiple figures in current
graph
%
%
%
%
Plot matrix as image
Choose gray level colormap
Show pixel coordinates as axes
Remove axes
%You may zoom in to particular portions of a plot by clicking on the
%magnifying glass icon in the figure and drawing a rectangle.
* Challenge: Plot functions x (blue squares and line), x^2 (red circles and line) and x^1/2 (green diamonds and line)
between (0,2) on the same plot.
Let’s do Exercise 1!
Creating scripts and functions using m-files
%
%
%
%
%
Matlab scripts are files with ".m" extension containing Matlab
commands. Variables in a script file are global and will change the
value of variables of the same name in the environment of the current
Matlab session. A script with name "script1.m" can be invoked by
typing "script1" in the command window.
* Challenge: Create a script called “myfirstscript.m” to prints out today’s date. (Hint: >>help date)
%
%
%
%
%
%
%
%
Functions are also m-files. The first line in a function file must be
of this form:
function [out_1,..., out_m] = myfunction(in_1,..., in_n)
The function name should be the same as that of the file
(i.e. function "myfunction" should be saved in file "myfunction.m").
Have a look at myfunction.m for examples.
a = [1 2 3 4];
b = myfunction(2 * a)
% Global variable a
% Call myfunction which has local
% variable a
>>a
function y = myfunction(x)
% Function of one argument with one return value
a = [-2 -1 0 1];
% Have a global variable of the same name
y = a + x;
>>help myfunction
%
%
%
%
%
%
Functions are executed using local workspaces: there is no risk of
conflicts with the variables in the main workspace. At the end of a
function execution only the output arguments will be visible in the
main workspace.
If we create a file named f.m in the current working directory with
this code
%f.m
function y = f(x, a)
% Returns the square of the first argument times the second
y = a * x ^ 2;
% Then, from the command window we can just evaluate the function
f(3, 4)
ans = 36
% In the command window type: >>help f
* Challenge: Define a new function called stat.m that calculates the mean and standard deviation of a vector x.
* Challenge: Define a new function called bellcurve.m that creates 10000 normally distributed random numbers
with mean 3 and standard deviation 2. Make a histogram to verify the bell curve. (Hint:>> help randn and
>>help hist)
Syntax of flow control statements (for, while and if expressions)
% for VARIABLE = EXPR
%
STATEMENT
%
...
%
STATEMENT
% end
%
% EXPR is a vector here, e.g. 1:10 or -1:0.5:1 or [1 4 7]
%
Example “for loop” to calculate 100 terms of the Fibonacci numbers, where each successive term is the sum of the two prior terms: % Fibonacci.m
clear
% clear all variables from the computer’s memory
Fib_seq(1) = 0;
% first two terms are defined as 1 and 1
Fib_seq(2) = 1;
for i = 3:100
Fib_seq(i) = Fib_seq(i-1)+Fib_seq(i-2);
end
Fib_seq(1:10)
plot(Fib_seq)
% prints out the first ten terms for interest
% plots all 100 terms
%
% while EXPRESSION
%
STATEMENTS
% end
%
Example “while loop” for the Fibonacci numbers is almost (but not quite) identical:
% Fibonacci_while.m
clear
% clear all variables from the computer’s memory
Fib_seq(1) = 0;
% first two terms are defined as 1 and 1
Fib_seq(2) = 1;
i = 2;
while( i < 100)
i = i+1;
Fib_seq(i) = Fib_seq(i-1)+Fib_seq(i-2);
end
Fib_seq(1:10)
% prints out the first ten terms for interest
plot(Fib_seq)
% plots all 100 terms
%
%
%
%
%
%
%
%
%
%
%
%
if EXPRESSION
STATEMENTS
elseif EXPRESSION
STATEMENTS
else
STATEMENTS
end
(elseif and else clauses are optional, the "end" is required)
EXPRESSIONs are usually made of relational clauses, e.g. a < b
The operators are <, >, <=, >=, ==, ~=
The following example code combines a for loop with an “if” expression to sum the multiples of 3 that are less than 100, and separately sum the nonmultiples: % multiple_nonmultiple_sum.m
% sums multiples and nonmultiples of 3:
sum_multiples = 0;
sum_nonmultiples = 0;
for i = 1:99
% initialize sums to zero before accumulation
% all numbers less than 100
if ( mod(i,3) == 0 )
% if remainder is zero when dividing by 3
sum_multiples = sum_multiples + i;
else
sum_nonmultiples = sum_nonmultiples + i;
end
end
sum_multiples
sum_nonmultiples
* Challenge: Write a function that takes two variables and prints a statement indicating whether the first variable is
smaller, larger, or equal to the second variable.
200
* Challenge: Write a function that calculates
! (n
3
+ n2 )
0
More operations useful for HW Now you can perform some simple operations. Now let's implement a toy excercise that is somewhat similar to the homework. Suppose you want to write some code that tells you whenever some function, say a sinewave, has the value of 0.5 or greater. Off the top of my head, I can think of two basic ways to implement this: using a 'for' loop (the slow way), or using a few carefully chosen Matlab expressions. Both are fine for this course. First, let's look at a toy 'for' loop, and then we'll implement the procedure above using a 'for' loop. Type the following: for A=[1 2 3 4 5],
A,
end;
for A=a,
A,
end;
for A=1:5,
A,
end;
All of these 'for' loops do the same thing. The variable A steps through the matrix [1 2 3 4 5], and inside the loop we have asked Matlab to display the value of A. We have defined the matrix [1 2 3 4 5] three different ways: explicitly, using our variable a as before, and a new way, using the colon operator. The colon operator allows you to define a vector as running from a beginning value to an ending value, and optionally using a step different from 1. Try this below: A=1:5
A=5:-1:1
A=0:0.1:1
Now you should have a good grasp of the colon operator. Let's solve the problem we introduced at the beginning of the section with a 'for' loop and plot the result. T=0:0.01:10; % define T to be a vector running between 0 and 10 in steps of
0.01
sw = [];
% define sw to be an empty vector
th=[];
% define an empty vector for determining if we are exceeding
threshold or not
for t=T,
% for each value of T
sw(end+1) = sin(2*pi*t); % set next value of sw to be the sine of 2*pi*t
th(end+1) = sw(end)>0.5; % add either a 1 or a 0 to th
end;
% now let's plot
figure(1);
subplot(2,1,1);
plot(T,sw);
axis([T(1) T(end) -1.5 1.5]);
subplot(2,1,2);
plot(T,th);
axis([T(1) T(end) -0.5 1.5]); % set the axis so it looks prettier
Here we've introduced two new operations. One is the idea of creating an empty vector and adding to it. If you want to see this more closely, type 'A=[], A(end+1)=1, A(end+1)=1,'. We've also introduced the comment syntax: any text on a line following a '%' will not be treated as code. This will help you remind yourself what you have written, and will help the TAs grade your homework. Now let's do this same function in a way that takes advantage of Matlab's matrix style. First, let's use the 'clear' command to clear some of our old variables: clear T sw th
T=0:0.01:10;
sw=sin(2*pi*T); % this does all values of T at once
th = sw>0.5; % this does all entries of sw at once
% now let's plot
figure(1);
subplot(2,1,1);
plot(T,sw);
axis([T(1) T(end) -1.5 1.5]);
subplot(2,1,2);
plot(T,th);
axis([T(1) T(end) -0.5 1.5]); % set the axis so it looks prettier
So hopefully now you are begining to understand how Matlab's language can allow you to briefly perform some complicated manipulations. If you were doing actual homework, you would want to title these plots and label the y and x axes. 
Download