%*************************************************************** %* %* tutor.m: Tutorial for beginning MATLAB users. %* %* Written by: Kyle D. Dippery %* 473 Anderson Hall %* (606) 257-3893 %* kdip@engr.uky.edu %* %* Last updated May 20, 1997 %* %* Copyright 1997 by Kyle D. Dippery %* %* Reproduction of this document is permitted for %* noncommercial use only, provided the entire document, %* including this copyright notice, remains intact. %* %*************************************************************** clc echo on % % WELCOME TO MATLAB! % % % The purpose of this tutorial is to familiarize the % user (that's you) with the basics of MATLAB. % % In the screens to follow, lines preceded by a percent % sign ('%') are comment lines, and are ignored by the % MATLAB interpreter. All other lines are actual MATLAB % commands, which will be executed before your very eyes. % % Press a key to continue... pause clc % Probably the first useful thing you need to know is % how to enter data from the keyboard. You can do this % by assigning values directly to variables. For example, % to assign the value 5 to the variable 'a', we enter: a=5 % That first line ("a=5") is what we entered. MATLAB % then shows us that it understood what we said, by % echoing the value of a (5). % Press another key... pause clc % MATLAB doesn't particularly care whether the value % we enter is a scalar, vector, or matrix. The syntax % for the assignment is mostly the same, regardless. % The only difference for vectors or matrices is that % we need square brackets ([]) to tell MATLAB that the % input is an array. So, to enter a row vector, let's % call it 'b', we type: b=[1 3 4 5 8 9] % Here we've separated the elements of the array by % spaces. Commas would have worked just as well, but % we tend to think commas make the line look a bit more % cluttered than it really needs to. pause clc % Column vectors, like 'bc', are entered as: bc=[1; 4; 3; 5; 3; 5]; % Notice the dual use of the semicolon in the last % example. First, it separates the rows of column % vectors (or other multi-row arrays). (Spaces after % the semicolons aren't necessary, but we think they % help make the line more readable.) % % Second, when a semicolon ends a command it tells % MATLAB not to echo the results of the command to % the screen. % Another key to continue... pause clc % If we want to look at a variable after it is assigned, % we can use the 'disp' command. disp(bc) pause clc % Colons have special uses in MATLAB, too - they can % be used to build vectors of evenly-spaced numbers: a2=1:0.5:3.4 % Notice that the last element of the vector is 3.0, not % 3.4. This is because the next element of the specified % sequence is 3.5, which is greater than the upper limit % (3.4) we assigned. % % Notice also that, in this case, we didn't need the % square brackets. That's because MATLAB expects a % vector input when the colon notation is used. Still, % the brackets can be used if there's any doubt; there's % nothing wrong with a little redundancy. pause clc % If the increment (the second number in that last % assignment statement) is omitted, it defaults to 1: a3=0:5 pause clc % Matrices can be entered as a sequence of row vectors, % separated by semicolons. A=[1 3 5 7; 2:2:8; 1 2 4 9] pause clc % Or as a sequence of column vectors, separated by commas % or spaces: B=[bc,2*bc 3*bc] pause clc % Complex numbers also receive no special treatment: C=ones(3,3) + i * A(:,1:3) pause clc % Some notes about this last command: % % C=ones(3,3) + i * A(:,1:3) % % 1. 'i' is implicitly recognized as sqrt(-1). % So is 'j'. % % 2. 'ones(m,n)', where m and n are positive integers, % generates an mxn array of 1's, in this case used for % the real part of C. Some other 'special' matrices can % be generated by 'zeros', 'eye', 'rand', 'randn', or % 'magic'. % % 3. Submatrices can be extracted from matrices by % using indices. In this case, the imaginary part of % C is a submatrix of A, consisting of the first three % columns of A (the same matrix A we used before, still % in memory for us to use.) pause clc % A bit more about: % % C=ones(3,3) + i * A(:,1:3) % % The first index into an array always indicates the rows % to be used, the second index indicates the columns. % Indices may be scalars or vectors. A colon, by itself, % means "use 'em all". Hence, A(:,1:3), A(1:3,1:3), and % A([1 2 3],[1 2 3]) would all give the same result (since % A, in this particular case, has only three rows). % % 4. Multiplication of a matrix by a scalar is % accomplished by the '*'. Matrices, scalars, and % vectors are all added by '+'. pause clc % Addition and subtraction act the same for scalars, % vectors, and matrices. a+b, where a and b are scalars % adds a and b together. % % If a and b are vectors, a=1:5, b=10:-2:2 pause clc % or matrices, with the same dimensions, then a+b adds each % element of a to its corresponding element in b: a+b % Notice that, if an operation is not assigned to a % specific variable, it is assigned to the temporary % variable, 'ans'. pause clc % Scalars can be added to (or subtracted from) anything: ans-3 rand(3,3)+ans(4) % See if you can follow what just happened, there... pause clc % Order of operation is pretty standard - exponents are % evaluated first, multiplication and division next, % addition and subtraction last; operations are evaluated % left to right, except when parentheses are used to group % things together. The usual stuff... pause clc % Multiplication and division are slightly different: % they are assumed to be matrix operations: A=magic(3) B=[8 2 1; 2 2 1; 5 3 7] pause clc Mprod=A*B pause clc % If what we want is an array whose elements are the % elements of A times the elements of B, we need to % use a 'dot-multiply', or '.*': Aprod=A.*B pause clc % This is called 'array multiplication', to distinguish % it from 'matrix multiplication'. % % Let's look again at our matrix product, for comparison: Mprod, Aprod pause clc % Division with matrices is similar to multiplying % one matrix by the inverse of the other: % % A/B is almost A*inv(B) (where inv(B) is the MATLAB % command which finds the inverse of B). % % A\B is almost inv(A)*B. % % (The reason it's "similar to" and not "the same as" is % that A and B don't have to be square matrices for the / % or \ operations, but do for the inv() operation.) % % For more precise definitions of / and \, try % 'help /' or 'help slash'. pause clc % Array division is accomplished by the 'dot-divide' % operations, './' and '.\'. % % A./B yields an array whose elements are the elements of % A divided BY the elements of B. % % A.\B yields an array whose elements are the elements of % A divided INTO the elements of B (or, the elements of B % divided BY the elements of A). % % Note that A.\B is the same as B./A, but A\B is NOT the % same as B/A. pause clc % Matrices may be multiplied by scalars without using the % '.*', but division requires a bit of care. % % For instance, 2*A and A*2 will both yield disp(A*2) % A/2 gives us an array whose elements are the elements of % A divided by 2, but 2/A does _not_ give us an array whose % elements are 2 divided by each element of A (unless A % happens to be a scalar). pause clc % Exponents are kinda ugly. Usually, what you'll probably % want is every element of a vector raised to a certain % power, or a certain base raised to the power of every % element in a vector. These would be accomplished by the % '.^' operator: disp(a) disp(a.^3) disp(3.^a) % The '^' operator by itself has more to do with matrix % powers, and either the matrix or the exponent, but not % both, must be a square matrix. 'help arith' will give % more information on this. pause clc % The '.' means something a bit different when dealing % with transposes. % % Normally, a transpose is denoted by a single quote, '. % When the matrix is complex, this is actually a complex % conjugate ("Hermitian") transpose operator. A % "straight" transpose is denoted by a dot-transpose, .'. % % Note: for real-valued matrices, there is no difference % between a transpose (') and a dot-transpose (.'). pause clc % Some examples, using our matrix C disp(C) disp(C') disp(C.') pause clc % For an example of why we like array multiplication, % let's try to draw a spiral. t=0:720; % angle, in degrees, twice around x=t.*sin(pi/180*t); % x coordinate y=t.*cos(pi/180*t); % y coordinate % Notice that mathematical functions can operate on % arrays. sin(pi/180*t) takes the sine of every element of % the vector, pi/180*t. (pi is 3.1415etc., implicitly defined.) % % t*sin(pi/180*t) would try to multiply a 1x721 matrix by % another 1x721 matrix, which doesn't work. Instead, % t.*sin(pi/180*t) multiplies the ith element of t by the % ith element of sin(pi/180*t), which is what we really % want. % % Notice also that the input to the sin and cos functions % is converted from degrees to radians. Trig functions % in MATLAB always operate on radians. pause clc % Notice also how the array operations neatly reduce % the need for 'for' loops. % % x=t.*sin(pi/180*t); % % gives the same result as: % % for ii=1:721, % x(ii)=t(ii)*sin(pi/180*t(ii); % end % % (We like to use 'ii' and 'jj' instead of 'i' and 'j' % for loop counters, because 'i' and 'j' already mean % sqrt(-1) to MATLAB, and we'd hate to try to build a % complex array out of something, only to find out that % i=17.2 or j=150 suddenly, because we used them for % something else beforehand...) pause clc % Now let's look at our spiral. plot(x,y) % This is the simplest method of obtaining a graph. We % can label this graph, xlabel('X Coordinate') ylabel('Y Coordinate') title('Wow, It Worked!') % Input to the 'xlabel', 'ylabel', and 'title' commands % must be a string argument. Strings in MATLAB are % delimited by single quotation marks ('). % % Strings are concatenated (stuffed together) with square % brackets. ['Hi' ' there!'], for instance, yields the % string 'Hi there!' (see 'puzzle(2)' for another example). % Functions exist for turning numbers into strings, which % can then be used in figure titles or labels: text(0,max(y),['Max y value = ' num2str(max(y))]); pause clc % If, for some reason, we don't like yellow lines, % we could ask for the plot in some other color (we % like green, ourselves): plot(x,y,'g') % Notice that all of our nice labels are gone. % Successive 'plot' statements generally erase % anything that was set by earlier ones. (This % can be changed by playing with the 'hold' % function.) pause clc % Or we could ask it to plot the data as red plusses: plot(x,y,'r+') % For a list of possible linestyles and colors, % enter 'help plot' from the command prompt (when % you get it back, that is). pause clc % Multiple plots can be placed in a single window by % using 'subplot'. subplot(211), plot(t,x,'c:') ylabel('X') title('A Spiral?') subplot(212), plot(t,y,'Color',[1 0.5 0],'linestyle','-.') ylabel('Y') title('It Doesn''t Look Like a Spiral...') xlabel('Angle, Degrees') % Look carefully at the second 'title' command, above, and % compare it to the actual title. Look again. There is a % difference - where the apostrophe appears in the title, % there are two in the command. This is how you get % single apostrophes to appear in MATLAB strings, since % one by itself would mean the end of the string. % % Alternate methods of specifying line colors and styles % are also illustrated above. pause clc % Did you notice how nothing happened in the figure window % until all the commands for building all of the plots had % been executed? MATLAB doesn't like to update figures % until it absolutely has to (who does?), or when it runs % out of commands to execute, or when it runs into a % 'pause' statement (as it did, here). The 'drawnow' % command will force MATLAB to display graphs before it % reaches the end of the command stack: pause clf subplot(211), plot(t,x,'c:') ylabel('X') title('A Spiral?') drawnow % just like this subplot(212), plot(t,y,'Color',[1 0.5 0],'Marker','.') ylabel('Y') title('It Doesn''t Look Like a Spiral...') xlabel('Angle, Degrees') pause clc % Or we could look at multiple plots on a single set % of axes: clf plot(x,y,'g',x,t.*cos(2*pi/180*t),'r--') title('There''s Something Fishy Here...') xlabel('X'), ylabel('Y') pause clc % We can add gridlines: grid pause % Or turn just some of them on or off: set(gca,'ygrid','off') pause % Or even zoom in some, set(gca,'xlim',[340 460]) % but that's getting a bit fancier than we generally % need. Still, if you want to play with lots of figure % or axes properties, you can look into the 'set' and % 'get' commands, later. There's lots of fun to be had, % in there... pause clc % Figures can be cleared by 'clf'. Empty figure windows % can be opened by entering 'figure'. Figure windows % can be closed by entering 'close(n)', where n is the % number of the window to close. (The figure number is % usually displayed in the window's title bar.) % % 'close all' closes all figure windows. clf pause close(1) pause clc % Hardcopies of plots are obtained through the 'print' % command. 'print -deps filename' would print the % current figure to filename.eps, in encapsulated % PostScript format. The file could then be printed % on a laser printer, or imported into documents, or % whatever. 'print', by itself, sends the plot to the % default printer. You may want to be careful of this, if % your printer has a page quota, or if you're just trying % not to be wasteful, or some such... % % MATLAB also supports formats besides Encapsulated % PostScript. Enter 'help print' to find out about % these. pause clc % We've played with quite a few arrays, so far: a, b, % bc, A, B, t, x, y, and maybe one or two more we don't % remember. Right now, they're all still sitting in % memory. What if we've lost track of what we've done? % Is there a way to find out what we have in memory? % % Maybe.... Try entering 'who': who % This shows all the variables currently residing in % memory. pause clc more on % Or we could type 'whos'. This shows all the variables % in memory, along with their sizes and some other neat % things about them. Let's first introduce the 'more' % function, though: this forces screen display to pause % each time the screen fills up. 'more on' and 'more off' % are used to control this paging routine. % % When 'more' is 'on', the spacebar pages ahead one full % screen, 'q' quits the pager (it probably would not be a % good idea to press 'q' just now, however... it likely % would also quit the tutorial at this point) and just % about any other key moves forward one line. whos more off pause clc % Let's get rid of some of this baggage: clear Aprod Mprod a a2 a3 ans b bc t x y % 'clear', by itself, or 'clear all', would get rid of % everything. But I wanted to keep some things... who pause clc % What if we only want to know the size of one array? BSize=size(B) % 'size' returns a two-element vector, containing the % number of rows (1st element) and the number of columns % (2nd element) of an array. 'size(ans,1)' will return % just the number of rows. 'size(ans,2)' will return % just the number of columns. % 'length' returns the maximum element of the 'size' % vector (useful for dealing with vectors) pause clc % We could use the 'tic' and 'toc' commands to find % out how much time it takes to calculate that inverse. tic; inv(C) toc % The 'elapsed_time' is shown in seconds. pause clc % If we just wanted to know what time it is, we could % look at the 'clock' (since some of us don't wear watches): clock % This tells us, in order, the current year, month, day, % hour, minute and second (just multiply that '1.0e+03' % factor through each element to get the right values). % % (And no, we don't know what's going to happen at the end % of the millenium...) pause clc % Hardcopy of any MATLAB session can be obtained by % using the 'diary' function. If 'diary' is on ('diary % on' is the command), then anything that prints on the % screen also prints to a file called 'diary'. % % 'diary filename' sends all output to the specified file. % % 'diary off' turns the diary function off. pause clc % That's it for this tutorial. If you want to look % at it again, without pressing all those carriage % returns, set 'more on', then 'type tutor'. % % To quit MATLAB when you're done (or ready for lunch), % type either 'exit' or 'quit'. % % Enjoy! echo off