Lab 1 overview:
- What's MATLAB? Why MATLAB?
- Creating and accessing vectors
- Operating on vectors
- Built-in functions
- Saving your work as a script
- What's MATLAB? Why MATLAB?
- Introduction to Matlab - Interface
- Creating vectors
- Vector access
- Error messages
- Vector math
- Inner product
- Getting help
- An important aside about notation
- Looking for a function
- Plotting multiple lines on the same axis
- More visualizations: histograms and scatterplots
MATLAB is a programming language and a development environment. It was created as an interactive interface to government-written numerical libraries (written in Fortran in the 1970's).
Why write your own code (instead of using a canned package)? You'll be sure you understand the whole analysis, and you can test/verify everything, and you can explain it properly in a paper or talk.
Why use code in this course? So you can try out the math. Visualize it. Make it concrete. It's another learning tool.
Why MATLAB, not a different language?
- A de facto standard in many fields
- Interactivity allows easy development/testing: play around with ideas in the command line
- Automatic memory management (unlike C and other traditional languages)
- Integrated plotting commands, and large libraries of tools
Let's familiarize ourselves with the MATLAB interface. Work by typing these commands into the interpreter: the window with the line starting with ">>". Type your commands after ">>" and hit enter.
Copy these lines to the prompt (">>" in the other window) and run them one at a time:
3+4 5-9 4*6 5*(3+4) 26/5 5^2 pi % You can use the "up" arrow at the prompt (">>") to go back to previous % commands you typed. % % If you start typing and then use the up arrow before you're done, it will % find you all past commands that start with the letters you just typed.
ans = 7 ans = -4 ans = 24 ans = 35 ans = 5.2000 ans = 25 ans = 3.1416
We can assign values to variables with =. When you read code, think of the = sign as 'is assigned to' or 'becomes'
a = 7 % a becomes 7 a = 7; % When you end a statement with a semicolon, Matlab doesn't show the output a % but a still becomes assigned to 7 % Now we can use a in any expression a+1 a/7 a*a+a-5 % without changing its value a % ... unless we re-assign a value to it a = 41; a % Can we assign a variable to another variable? What happens? b = a; b c = a + 1; c % If b = a, then what happens when we change a? a = 10; b c % The way this works is that MATLAB has a lookup table. When you type % something, like "a", it looks in the lookup table for the associated % value. When you type "a = 1", it puts "1" in the lookup table as the % value for "a". % We don't have to use single letters as variable names: anything % made of letters and numbers and selected other characters. In % general, it's a VERY good idea to use descriptive names for your % variables. Many coding errors can be retraced to unclear variable names. % And the more descriptive your variable names, the less likely they are to % be "already taken" (more on that later) darthVader = 7; han_solo = 4*4; R2D2 = (han_solo + darthVader)/2; % Note that we use underscores instead of spaces in variable names. % Also, we can't use a hyphen, because "han-solo" would be read as "han" minus % "solo"! % Another neat feature of the prompt: If you type part of a variable name and % then hit "tab", you can see possible completions. Try typing "darth" and % then hitting tab.
a = 7 a = 7 ans = 8 ans = 1 ans = 51 a = 7 a = 41 b = 41 c = 42 b = 41 c = 42
MATLAB uses a table to look up the variables. You can view this table in the "workspace" in your matlab editor. This is useful to you for keeping track of the variables you've assigned. You can view the contents with "who" ("whos" is similar and gives you more information)
who % You can also cause output to be shown with the "display" command: display(a);
Your variables are: R2D2 ans c han_solo y a b darthVader x a = 10
a = [1 2 3] % This is a row vector a = [1, 2, 3] % This is also a row, the commas are optional a = [1; 2; 3] % This is a column % How do I enter a whole range of numbers? a = [1:10] % 1 through 10, counting by 1, as a row a = [1:2:10] % Start at 1, count up by twos, don't go past 10 a = [10:-1:4] % Start at 10, go down by 1, don't go past 4 % How can I build vectors which have a bunch of different 'parts' a = [1:10 4:5] %this concatenates the vector 1:10 to 4:5 % How do I build a vector of zeros? a = zeros(1,5) % a row vector a = zeros(5,1) % a column vector % And vectors of ones? a = ones(1,5) % that was easy % But this works only for zeros and ones, no twos, threes and fours. % Sorry :) % How about random numbers? a = rand(1,5) % these are uniformly distributed between 0 and 1 % Transpose operator flips rows and columns a = [1:10]'
a = 1 2 3 a = 1 2 3 a = 1 2 3 a = 1 2 3 4 5 6 7 8 9 10 a = 1 3 5 7 9 a = 10 9 8 7 6 5 4 a = 1 2 3 4 5 6 7 8 9 10 4 5 a = 0 0 0 0 0 a = 0 0 0 0 0 a = 1 1 1 1 1 a = 0.8147 0.9058 0.1270 0.9134 0.6324 a = 1 2 3 4 5 6 7 8 9 10
Try creating different arrangements of the numbers 1 through 6. Can you create a row vector? A column vector?
Let's create a vector. Remember what we said about descriptive variable names? So let's name our vector "vec", so we remember that it's a vector.
vec = [101:112]; % Access elements in a vector using parentheses vec(2) % This gives us the second element of the vector vec(4) % and the fourth % Access multiple elements at once % Instead of just one number in the parentheses, we can put a range of numbers. vec(3:6) % This gives us elements 3, 4, 5, and 6. vec(2:2:6) % we can access non-consecutive elements vec(6:-1:4) % or even in the reverse order % "end" is a special keyword for accessing the last element. vec(end) vec(1:end) % and we can do mathy operations on it vec(end-2)
ans = 102 ans = 104 ans = 103 104 105 106 ans = 102 104 106 ans = 106 105 104 ans = 112 ans = 101 102 103 104 105 106 107 108 109 110 111 112 ans = 110
Below is a vector called "b". Write four expressions: one each to select just all the 0's, all the 1's, all the 2's, or all the 3's. Can you think of clever ways to access these elements?
b = [2 2 2 3 1 1 3 1 1 0 1 1];
Sometimes there will be an error! Thats OK! That's totally normal! Error messages are a great debugging tool, because they'll tell you exactly what went wrong. Let's do some examples of failed vector access:
vec = [1 2 3]; % vec(4) % "Index exceeds matrix dimensions" because we tried to take the % fourth element of a 1x3 vector, and 4 exceeds 3. % vec(0) % "Subscript indices must either be real positive integers or % logicals." We get this error because 0 is not a positive integer. Unlike % in other programming languages, there is no "zeroth" element. The first % element is indexed with 1. % vec(-1) % "Index exceeds matrix dimensions" again. I have no idea why % MATLAB doesn't first warn you that -1 isn't positive.
Let's try some simple vector math: +, -, /
% Set up variables to play with: a = 4; x = [1:5]; y = [11:15]; z = rand(1,7); % Scalar multiplication and addition/subtraction are performed elementwise a*x x + y x - y % Note that x + z fails, due to wrong sizes % We can do elementwise multiplication and division, but not with * and / % We have to use .* and ./ instead x.*y y./x % We can also do elementwise raising-to-powers x.^2 % we can chain these operations, but be careful where you put your % parentheses! x+y./x (x+y)./x
ans = 4 8 12 16 20 ans = 12 14 16 18 20 ans = -10 -10 -10 -10 -10 ans = 11 24 39 56 75 ans = 11.0000 6.0000 4.3333 3.5000 3.0000 ans = 1 4 9 16 25 ans = 12.0000 8.0000 7.3333 7.5000 8.0000 ans = 12.0000 7.0000 5.3333 4.5000 4.0000
% The inner product (dot product) sums the products of the elements. % Here are four lines that all compute the inner product: x(1)*y(1) + x(2)*y(2) + x(3)*y(3) + x(4)*y(4) + x(5)*y(5) sum(x.*y) dot(x,y) x*y' %this one arises from matrix multiplication, which will be %covered in next class! % inner product of perpendicular vectors is 0 [2 2] * [-5 5]'
ans = 205 ans = 205 ans = 205 ans = 205 ans = 0
% Functions are calculations that have names. For example in math notation % "y = f(x)", f is the name of the function. x is the input. y is the output. % Some functions perform mathematical operations: abs(-2); sin(pi/2); round(2.7); ceil(2.7); floor(2.7); % Some functions take a vector as input sum(x); min(x); max(x); mean(x); std(x); % the standard deviation % Many functions take either a scalar or a vector as input % For the vector, they perform their operation elementwise floor(x) sin(x) exp(x) % Some functions compute other properties of their inputs: size(vec) size(4) % notice while we're here that scalars are stored in matlab as 1x1 matrices length(vec) % the size of the largest dimension
ans = 1 2 3 4 5 ans = 0.8415 0.9093 0.1411 -0.7568 -0.9589 ans = 2.7183 7.3891 20.0855 54.5982 148.4132 ans = 1 3 ans = 1 1 ans = 3
MATLAB contains extensive documentation, which you can access using the "help" command to view it in the command window, or the "doc" command to pull up a pretty window.
help size doc size which vec which abs
No help found for size.m. vec is a variable. built-in (/e/1.4/share/erda/matlab8.3/toolbox/matlab/elfun/@double/abs) % double method
Watch out, there are two totally identical-looking parenthesis notations And they're totally different!
vec(3) % 1) accessing a vector/matrix element abs(3) % 2) calling a function % MATLAB will let you override built-in functions. Avoid this! abs = [10, 11, 12]; abs(3) which abs % Abs is now a variable?? % Yep,'abs' is in the list of variables! MATLAB looks there first % In fact *every time* you type something, MATLAB has to look it up % To remove a variable from the lookup table, use "clear": clear abs which abs % similarly, the values of built-in variables are not protected % from re-assignment: pi = 42 cos(pi) clear pi cos(pi)
ans = 3 ans = 3 ans = 12 abs is a variable. built-in (/e/1.4/share/erda/matlab8.3/toolbox/matlab/elfun/@double/abs) % double method pi = 42 ans = -0.4000 ans = -1
% average(vec) % hm, this function doesn't exist? Let's look at the help: which average; % not found! interesting lookfor average; % search the help docs for the word "average" % oh, we wanted "mean", right. mean(vec)
'average' not found. mean - Average or mean value. emldemo_navg - Compute the average of every N elements of A and put them in B. affygcrma - Performs GC Robust Multi-array Average (GCRMA) procedure. affyrma - Performs Robust Multi-array Average (RMA) procedures. gcrma - performs GC Robust Multi-array Average (GCRMA) background gcrmabackadj - performs GC Robust Multi-array Average (GCRMA) background aveknt - Knot averages. mean2 - Average or mean of matrix elements. ewmaplot - Exponentially weighted moving average chart. ans = 2
% You can't just "plot a function" directly: first you have to define a % discrete set of x values, then compute the corresponding y values, then % plot the x points against the y points % Let's define 10 points, and plot the "sin" function at those points: x=[0:1:10]; y=sin(x); plot(x,y) plot(x,y,'o') plot(x,y,'o-') % (The above "plot" commands will overwrite each other in the figure window, % so run each one separately if you want to see their separate output.) % That image is too choppy. Let's try using more x values. x = [0:(2*pi/100):(2*pi)]; % (Remind yourself how the colon notation works here) y = sin(x); plot(x,y,'o-'); % That was actually 101 points. What if we want 100 points? x = [0:(2*pi/99):(2*pi)]; % way 1 - this is unreadable, don't do this x = linspace(0,2*pi,100); % way 2 - this is readable!
y = sin(x); z = cos(x); plot(x,y,x,z); % Plot without specifying your x values, it assumes 1:n plot(y); % Treat x like a parametric variable plot(y,z); axis equal
plot(rand(1,100)) hist(rand(1,100)) hist(rand(1,1000)) hist(rand(1,1000000)) plot(rand(1,1000), rand(1,1000), 'o') title('uniform') plot(randn(1,100)) hist(randn(1,100)) hist(randn(1,1000)) hist(randn(1,10000)) hist(randn(1,100000),-4:0.1:4) plot(randn(1,1000), randn(1,1000), 'o') title('gaussian')
A script is a file that ends in ".m" which contains MATLAB code that's meant to be run all together.
Why write a script? 1) Save your work! 2) Run whole blocks of code at a time without typing it out at the prompt
Ways to use a script:
1. Use the green "RUN" button (or simply hit "F5") to run it all. This works just like typing it all at the prompt
2. Use ctrl-enter or apple-enter to run just one subsection at a time (subsections are separated by a double-percent "%%" at the start of the section)
3. Highlight a piece of the code and hit F9 to run just that portion