CU Mechanical Engineeringcourse specific Matlab tutorials |
Vector Operations
Matlab makes it easy to create vectors and matrices. The real power of Matlab is the ease in which you can manipulate your vectors and matrices. Here we assume that you know the basics of defining and manipulating vectors and matrices. In particular we assume that you know how to create vectors and matrices and know how to index into them. For more information on those topics see our tutorial on either vectors or matricies.
In this tutorial we will first demonstrate simple manipulations such as addition, subtraction, and multiplication. Following this basic "element-wise" operations are discussed. Once these operations are shown, they are put together to demonstrate how relatively complex operations can be defined with little effort.
First, we will look at simple addition and subtraction of vectors. The notation is the same as found in most linear algebra texts. We will define two vectors and add and subtract them:
>> v = [1 2 3]' v = 1 2 3 >> b = [2 4 6]' b = 2 4 6 >> v+b ans = 3 6 9 >> v-b ans = -1 -2 -3
Multiplication of vectors and matrices must follow strict rules. Actually, so must addition. In the example above, the vectors are both column vectors with three entries. You cannot add a row vector to a column vector. Multiplication, though, can be a bit trickier. The number of columns of the thing on the left must be equal to the number of rows of the thing on the right of the multiplication symbol:
>> v*b ??? Error using ==> * Inner matrix dimensions must agree. >> v*b' ans = 2 4 6 4 8 12 6 12 18 >> v'*b ans = 28
There are many times where we want to do an operation to every entry in a vector or matrix. Matlab will allow you to do this with "element-wise" operations. For example, suppose you want to multiply each entry in vector v with its cooresponding entry in vector b. In other words, suppose you want to find v(1)*b(1), v(2)*b(2), and v(3)*b(3). It would be nice to use the "*" symbol since you are doing some sort of multiplication, but since it already has a definition, we have to come up with something else. The programmers who came up with Matlab decided to use the symbols ".*" to do this. In fact, you can put a period in front of any math symbol to tell Matlab that you want the operation to take place on each entry of the vector.
>> v.*b ans = 2 8 18 >> v./b ans = 0.5000 0.5000 0.5000
Since we have opened the door to non-linear operations, why not go all the way? If you pass a vector to a predefined math function, it will return a vector of the same size, and each entry is found by performing the specified operation on the cooresponding entry of the original vector:
>> sin(v) ans = 0.8415 0.9093 0.1411 >> log(v) ans = 0 0.6931 1.0986
The ability to work with these vector functions is one of the advantages of Matlab. Now complex operations can be defined that can be done quickly and easily. In the following example a very large vector is defined and can be easily manipulated. (Notice that the second command has a ";" at the end of the line. This tells Matlab that it should not print out the result.)
>> x = [0:0.1:100] x = Columns 1 through 7 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 [stuff deleted] Columns 995 through 1001 99.4000 99.5000 99.6000 99.7000 99.8000 99.9000 100.0000 >> y = sin(x).*x./(1+cos(x));
Through this simple manipulation of vectors, Matlab will also let you graph the results. The following example also demonstrates one of the most useful commands in Matlab, the "help" command.
>> plot(x,y) >> plot(x,y,'rx') >> help plot PLOT Linear plot. PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever line up. If X is a scalar and Y is a vector, length(Y) disconnected points are plotted. PLOT(Y) plots the columns of Y versus their index. If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)). In all other uses of PLOT, the imaginary part is ignored. Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is a character string made from one element from any or all the following 3 columns: b blue . point - solid g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star y yellow s square k black d diamond v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus at each data point; PLOT(X,Y,'bd') plots blue diamond at each data point but does not draw any line. PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by the (X,Y,S) triples, where the X's and Y's are vectors or matrices and the S's are strings. For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a solid yellow line interpolating green circles at the data points. The PLOT command, if no color is specified, makes automatic use of the colors specified by the axes ColorOrder property. The default ColorOrder is listed in the table above for color systems where the default is blue for one line, and for multiple lines, to cycle through the first six colors in the table. For monochrome systems, PLOT cycles over the axes LineStyleOrder property. PLOT returns a column vector of handles to LINE objects, one handle per line. The X,Y pairs, or X,Y,S triples, can be followed by parameter/value pairs to specify additional properties of the lines. See also SEMILOGX, SEMILOGY, LOGLOG, PLOTYY, GRID, CLF, CLC, TITLE, XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT, STEM. Overloaded methods help idmodel/plot.m help iddata/plot.m >> plot(x,y,'y',x,y,'go') >> plot(x,y,'y',x,y,'go',x,exp(x+1),'m--') >> whos Name Size Bytes Class ans 3x1 24 double array b 3x1 24 double array v 3x1 24 double array x 1x1001 8008 double array y 1x1001 8008 double array Grand total is 2011 elements using 16088 bytes
The compact notation will let you tell the computer to do lots of calculations using few commands. For example, suppose you want to calculate the divided differences for a given equation. Once you have the grid points and the values of the function at those grid points, building a divided difference table is simple:
>> coef = zeros(1,1001); >> coef(1) = y(1); >> y = (y(2:1001)-y(1:1000))./(x(2:1001)-x(1:1000)); >> whos Name Size Bytes Class ans 3x1 24 double array b 3x1 24 double array coef 1x1001 8008 double array v 3x1 24 double array x 1x1001 8008 double array y 1x1000 8000 double array Grand total is 3008 elements using 24064 bytes >> coef(2) = y(1); >> y(1) ans = 0.0500 >> y = (y(2:1000)-y(1:999))./(x(3:1001)-x(1:999)); >> coef(3) = y(1); >> >>
From this algorithm you can find the Lagrange polynomial that interpolates the points you defined above (vector x). Of course, with so many points, this might get a bit tedious. Fortunately, matlab has an easy way of letting the computer do the repetitive things, which is examined in the next tutorial.
Now that you know how to perform vector operations, let's learn about loops!