%% On Models of Programming %We are going to talk about the syntax of matlab, and relating that %syntax to a "model of programming". I'm going to borrow analogy from %John Hughes, a professor at Brown: "Think of Gauss, sitting in a %box". He'll do any math operation that you ask of him, but you have %to be very specific. So today is about trying to define the language %in which we specify math operations. %% On Syntax %Matlab = "Matrix Laboratory". The fundamental core of matlab is a %matrix. Example matrices: [3,4,5] % a 1 by 3 matrix (1 row, three columns) [3 4 5] % a 1 by 3 matrix [3;4;5] % a 3 by 1 matrix (the semi-colon "stacks things up"). % We can make large matrices quickly with the ":" operator, as you saw % in your first lab. The command: 3:5 % makes the same 1 by 3 matrix 3:0.1:5 % makes a matrix of "3 to 5 by 0.1's" a:stepsize:b % [a a+stepsize a+2*stepsize ... ~b] % we can also makes different shapes of matrices: rand(2,2) % makes a 2 x 2 matrix of random numbers [rand(2,2) rand(2,2)] % makes a 2 x 4 matrix of random numbers [rand(2,2); rand(2,2)] % makes a 4 x 2 matrix of random numbers C = rand(4,6) % makes a 4 x 6 matrix of random numbers C(1,2) % the matrix element in row 1, column 2 C(:,2) % all the matrix elements in column 2 C(3,:) % all the matrix elements in row 3 C(3,3:end) % matrix elements in row 3 from the 3rd column to the end C(3,[1 3 6]) % matrix elements in row 3 from the 1st, 3rd, 6th column C(3,[1 1 3 3]) % elements in row 3 from the 1st, 1st, 3rd, 3rd column. % Use m = round(5 * rand(1, 40)) to make 40 random numbers between 0 and 4. % % Find out for which values of i we have m(i) = m(i+1). % Hint: to test whether k and p are equal, we write k == p; the resulting % value is either 0 or 1. % % ANSWER: m(1:end-1)== m(2:end) % note that there is no loop or if statement necessary, with Matlab, you % can work with whole arrays at a time, the program automatically performs % the operation on each element in the array. %%%%%%%%% % TYPES % %%%%%%%%% % Everything in MATLAB has a type. A type is like an identity. We have % type 'human', a pet might have type 'dog' or 'cat', etc'. It even extends % to mathematics, there is type 'integer' and type 'real' or 'imaginary'. % MATLAB works just like that. Here are the important types, together with % some explanations. %%%%%%%%%%%% % Integers % %%%%%%%%%%%% % Integers are very useful, and very common in some areas. An integer just % is a whole number, between negative infinity and positive infinity, such % as 3 % or 289748372 % But it isn't really infinity, there are some limits, but usually you % won't run into them, and you can ask the staff if you want to know more about % them. One of the main places integers turn up in MATLAB are in matrix % indices. A(5,2) or B(1:3,4), etc'. Another place, which you'll find out % later in the semester, is when you import an image into MATLAB, they'll % be a 'uint8' array. What does that mean? The 'u' is for unsigned, meaning % it is only numbers greater or equal to 0. The 'int' means it is an % integer', and the '8' means it has 8 bits, meaning the maximum number is % 2^8-1 (which is 255). Why this is, well, you'll find out soon enough. You % can ask Itay, Olga or Spike if you want to know more about it. %%%%%%%%%%%%%%%%%%%%%& % Floats and Doubles % %%%%%%%%%%%%%%%%%%%%%% % Floats are slightly more useful, as they can represent any fraction that % you want them to. For example: 5.5 % or 38784.287591854 % are both floats. Isn't it cool? You can put floats basically anywhere, % except where you have to put integers (i.e. when indexing matrices). % % Doubles is the short name for "double-precision float value" %%%%%%%%%%% % Strings % %%%%%%%%%%% % Strings are probably the most familiar concept to you. However, in MATLAB % they are a bit odd. To "create" a string, you put whatever you want % between single quotes, i.e. '. For example: 'hello world' % or 'hello 123... this is a test' % You might ask how you write an apostrophe. The answer is simple, you just % put two single quotes: 'I don''t know what you mean' % Easy, no? The one last thing you need to know about strings is that they % are essentially arrays of characters (one letter). Characters are stored as small integers (unsigned 8 bit size). That makes them a bit % complicated and ugly to use in some places, but we'll get to that later. %%%%%%%%%%%%%%%%%%% % Complex Numbers % %%%%%%%%%%%%%%%%%%% % Complex numbers are numbers which have both real and imaginary parts. % Usually they are written as the sum of the real and imaginary parts like % so: u = 3+4i; % Recall that i is the square root of -1, hence imaginary. Matlab nicely defines i for you as this value, but be careful!! If you assign another value to i, by typing "i=4;" for example, you then lose the ability to reference i as the imaginary value. % Complex values can be represented on a graph by plotting the number as a % point (x,y) where x is the real part and y is the imaginary part. For % example, to graph 'u' as defined above, you would graph the point (3,4). % To find the absolute value, or modulus of the complex number, take the % distance between the origin and the graphed point. For example: z = a + bi; % the absolute value of z would be the square root of a^2 + b^2. %%%%%%%%%% % Matrix % %%%%%%%%%% % This is the ubiqituous MATLAB type. I'm not sure what to say about it, % besides that it exists. % a matrix, in matlab, has two indices, which are written in parens, % like a(3,4). We can make a 6x6 array of random numbers... a = rand(6); % and see what the number in the 3rd row, 4th col is a(3,4) % We can also make a 5 x 7 array of randoms: a = rand(5,7); % We can also make a 5 x 7 array of ones: a = ones(5,7); %Or of zeros: a = zeros(5,7); % Note that this is a matlab idiom: foo(n) gets you something n x n, % and foo(n,k) gets you something n x k. % % % How can we tell that "rand" is a function, but "a" is an array? % After all, both a(3,4) and rand(3,4) are valid, right? % % Answer: in some sense, every matrix IS a function...but I don't % want to say any more than that right now. The short answer is % Look in the upper left corner for the "workspace" and see if % "a" is listed there as a matrix. % % Important life skill: learn that row-indices come first. That's % because "r is for row, and the letter 'r' appears in 'matrix'" % OK, that's stupid...but you'll remember it. r also appears in % 'array' which is another term sometimes used for matrices. % % Matlab also allows matrices with more than two indices; more % on that later in the semester. % % Finally, matlab does something that's both wonderful and terrible: % if you have a 3x4 matrix q, for example, you can refer to the entry % in the third row, second column as q(3, 2) ... or you can refer to % it as q(5). Why 5? Because if you label the entries from top to % bottom, left to right, it looks like this: % % 1 4 7 10 % 2 5 8 11 % 3 6 9 12 % % and matlab lets you refer to them in this way. We wish we could % turn off this "feature", but we can't. Sigh. % % Really useful thing: size(m) -> [nr nc] % What if you want to know just the number of rows? m = rand(3,4); q = size(m) q(1) % OK...but here's are two typical features of matlab: % (1) If you need some function that sounds commonplace, it's often there. % (2) The more code you write, the less you end up writing. :-) m = rand(3,4); size(m, 1) % find the dimension of the first "axis" (i.e., number of rows) size(m, 2) % or the number of columns % To find the number of total elements in the array you can multiply the % number of rows by the number of columns: n = size(m,1) * size(m,2); % BUT ... Matlab provides a simpler way. The function numel(m) returns the % total number of elements in the array m. %%%%%%%%%%%% % Logicals % %%%%%%%%%%%% % Logicals are a fancy name for true and false. They are also called booleans. In MATLAB % they're represented by a 1 or a 0, but don't let it fool you - they % aren't integers! They're logicals, and most integer operations do not % work on them, though some do. How to get logicals? Here are a couple of % examples: 10==10 % Checks whether 10 is equal to 10. Or: [1 2 3 4 5]>2 % returns an array of logicals, where there is a 1 if the value in the % above matrix is greater than 2 and 0 if it wasn't. u = 1:10 t = mod (u, 2) % u(t) % leads to error: the numbers in t are zeros and ones, but they're % DOUBLES, not LOGICALS. u(logical(t)) % gets us [1 3 5 7 9] as expected. %1:10 (logical(t)) % fails. Subscripting works ONLY on names (alas). u(2) % fine %u'(2) % no good: u' isn't a name. %%%%%%%%%%%%%%%%%%% % Type Operations % %%%%%%%%%%%%%%%%%%% % Sometimes you want to find out if something is of a certain type, or % convert it into something else. There are two groups of important % functions: % IS functions: IS functions are of the form is____(X), where _____ can be % integer, float, logical, etc'. You can do: isinteger(5) % or isinteger(5.0) % and the like. To get a better idea of what functions are available, go % to the main help menu (by going to Help --> MATLAB Help) and typing 'is' % in the search box. % Conversion/creation functions. Let's say you have a matrix of logicals, % like the one we had above, but we want to convert them into integers. You % could type: int32([1 2 3 4 5]>2) % and it will do it for you. Usually, the name of the function is the name % of the type, but sometimes it can be a bit odd. Just use the help if you % need anything. %%%%%%%%%%%%%%%%%%%%%%%%%% % The MATLAB Environment % %%%%%%%%%%%%%%%%%%%%%%%%%% % Another way to figure out types, and lots of other things, is the MATLAB % environment. We saw some of it last lecture, but we'll go a bit more % indepth now. % The main window stores the read-eval-print loop part of the interaction % loop. It displays the commands you type, the results, and the various % errors you're going to encounter. % At the bottom left you have the command history window, which stores all % the commands you've typed since you last cleared it. % Just below it is the MATLAB start menu, which lets you access the various % toolboxes and other parts of MATLAB. % At the top left you have the current directory view, or the workspace % view. The current directory merely shows you the contents of the current % directory you are in. The workspace view is a bit more interesting - it % shows you the current variables in your workspace - what their name is, % their type, and their class (don't worry about this). If you double click % any of them, you get a spreadsheet-style view and you can edit them and % view their contents - very nifty. You can get some of this functionality % (viewing the types and current variables) by typing 'who' or 'whos' into % the prompt. % To clear your workspace, you can type 'clear' in the prompt to clear it % all, or select all the variables in the workspace view and press the % delete button. To delete just one variable type 'clear variablename' in % the prompt or select that variable and press the delete button in the % workspace view. % In case you lose one of the above windows (it happens, trust me!), just % go to the Window menu at the top and click on the window that you lost. % It'll reappear. % If you opened an image and you'd like to attach it to the main window, % there is a button called Dock on the top right portion (by the close % button). Press it and it'll dock. Press it again and it'll undock. % MATLAB works with a 'current directory', which is how most Windows % programs work. You can see what the current directory is by looking at % the place which says it in the middle of the top menu, and change it from % there. %%%%%%%%%%% % Figures % %%%%%%%%%%% % Figures in MATLAB are far ranging things, they include plots, images, % etc'. We're going to introduce some simple things about them: % To create an empty figure, type figure. This will create a figure called % 'Figure X', where X is the next available number. figure % This method is not recommended, as it will make "debugging" (removing % errors in your program) difficult. % To create a figure with a specific number, type figure(3) % This will create a figure called 'Figure 3'. This method is recommended. % If you type figure(2) % you'll get another figure. Then figure(3) % will NOT make a new figure...it'll just bring the existing figure 3 to the % front where you can see it. % % MATLAB maintains a notion of "the current figure", even when there are % no figures showing yet. % Another useful command is gcf % Which returns a value which is an "id" for the current figure. % That means that figure(gcf) % brings the current figure out of the background (if it is behind any % windows). Each time you create or change a figure, type "figure(gcf)" % after it. % Similar to gcf is clf % which clears the current figure (i.e. erases all the drawings, but leaves % the window around). % % Closely related is close(3) % where 3 can be replaced with any other number corresponding to a % currently open figure. % If you wanted to plot two graphs on the same figure, you'd have to % use hold on % and here you would type the new plot command, and then type hold off % which literally keeps the current figure on hold until you finish adding % to it. If you do not do this, youre figure will get overridden. % % HINT: whenever you are writing a program, type "hold on" and "hold off" at % the same time, and then insert stuff between them. If you leave "hold" in % the "on" state, your results can get very confusing. % Let's do some things with figures. First, we read in two files: figure(1); plot(1:671,sin(1:167),'r'); figure(gcf); hold on % We need to use hold on to make the plot on the same figure, as we said % before: plot(1:671,sin(pi/2+ 1:167),'g'); figure(gcf); % notice the 'g' and 'r' - they are changing the LineSpec. Type 'help plot' % to learn more about it. %%%%%%%%%%%%%%%%%% % Variable Names % %%%%%%%%%%%%%%%%%% % Variable names are important. For example, you don't want to name your % variables 'nine', because then what if you do: nine = 7; % It's very confusing. Also, you do not want to give the variable name l = 1; % that's lowercase L - see, it is bad! Finally, you want to use clear, % meaningful names: averageofmedians = 5; % for example. % One final thing - don't name variables the same name as a MATLAB % function. For example, I onced named a variable 'sum', and then I tried % to use the function 'sum' - bad! bad! This could all have been avoided if % MATLAB designers had thought about it and not followed convention - you % can the staff to explain. %%%%%%%%%%%%%%%%%%%%% % Writing Functions % %%%%%%%%%%%%%%%%%%%%% % Let's think back to thinking about Matlab as Gauss % (the mathematician) sitting in a box performing tasks for us. The analogy % may seem dumb, but lets go with it for a little while longer. % Ok, so, Gauss is in the box with a pad of paper, a stack of index cards, % a permanent marker, a pencil, and some post-it notes. % When we tell matlab to define a variable such as "a = 4", Gauss takes the % fresh sheet of paper and writes "a = 4" on it. % Now let's say we define a new variable "b = a + 3". % Gauss looks at his pad to see what "a" equals. He writes the value of "a" on a post-it and adds 3 to it to find the value "b". He then writes the value of "b" on his pad of paper and throws out the post-it. % Now the variables "a" and "b" are both defined indefinitely. If we decide % to change the value later, Gauss simply crosses out the old value and % replaces it with the new one. % Now what happens when we write functions?? % First, to edit a function already in existence, we type edit function-name.m; % If this function doesn't already exist, Matlab creates it for us with the % name we specified. This action opens up an m-file, or we can think of it % as Gauss taking out a blank index card. At the top of the m-file % we define the function using a certain form. For example if we want to % make a function called "increment" that takes the value "x" and spits out % y = x + 1, our m-file would look like this: function y = increment(x) y = x +1 % don't forget to save your m-file!!! % What does Gauss do with these instructions?? % First, he takes out a blank index card for the function definition. He % writes down exactly what you wrote in the m-file. Then he takes this % card and files it away neatly in a place in his box where % he can find it easily later. % Now we define z = 5, and call increment(z). The code looks like this: z = 5; increment(z); % Note that even though we use x in the function definition, any value % between the parentheses after "increment" will work. % Now Gauss takes his pad of paper and writes z = 5 in black permanent % marker. Then he goes to his file cabinet type thing and takes out the % index card that defines "increment". % With the function definition in hand, Gauss notices that the variable % between the parentheses, (the "input" of the function) is referred to as "x", so he writes on a post-it % "x = z". % On the same post-it he writes "y = x + 1", which he then changes to "y = % z + 1". He looks up the value of z on his pad and writes that on the post-it too. % To keep track, Gauss's post-it now looks something like this: x = z; y = x + 1; y = z + 1; z = 5; % Now Gauss calculates the value of "y" , still on the post-it. He then % writes the value of "y" on the pad in black permanent marker, and throws % out the post-it and files the function definition card away for later.