A matrix (m x n) with m rows and n columns, a column vector (m x 1) with m rows and 1 column, and a row vector (1 x m) with 1 row and m columns all can be used in MATLAB.Matrices and vectors, when defined, are placed in brackets. To create a row vector simply use a space to separate elements. To create a column vector separate the elements with a semicolon. >> p=[1 4 6 7 8] p = 1 4 6 7 8 >> q=[1;2;5;1;6; ] q = 1 2 5 1 6 Vectors can be multiplied, but remember for vectors order of multiplication is important. For our vectors, p*q will yield a 1 x 1 matrix, a.k.a. a scalar, and q*p will yield a 5 x 5 matrix. >> r=p*q r = 94 >> s=q*p s = 1 4 6 7 8 2 8 12 14 16 5 20 30 35 40 1 4 6 7 8 6 24 36 42 48.
Remember that the inner dimensions must agree. A 5 x 1 matrix cannot be multiplied by a 5 x 1 matrix. However, in some cases instead of performing a vector multiplication, we might want to multiply individual elements in two vectors by each other. We can do this by using the “.*” notation. For this notation, the two vectors must have the same dimensions. >> t=p.*q ??? Error using ==> .* Matrix dimensions must agree. >> t=p.*q’ t = 1 8 30 7 48 Note that the apostrophe after q transposed q, converting q from a 5 x 1 to a 1 x 5 vector. For addition and subtraction, the vectors must have the same dimensions. >> p-q ??? Error using ==> – Matrix dimensions must agree. >> p-t ans = 0 -4 -24 0 -40 >> p+q ??? Error using ==> + Matrix dimensions must agree. >> p+t ans = 2 12 36 14 56 One tricky operation is the square function. This must be performed element by element for a vector “.^” instead of just “^” because the “^” notation requires a square matrix. >> p^2 ??? Error using ==> ^ Matrix must be square. >> p.^2 ans = 1 16 36 49 64 For functions that require an argument in parentheses, e.g. abs( ), sqrt( ), etc., it will perform the operations element by element. >> sqrt(p) ans = 1.0000 2.0000 2.4495 2.6458 2.8284 Matrices are made up of several vectors put together. A matrix can be defined as a collection of row vectors. >> A=[1 3 5; 2 1 7; 9 0 2;] A = 1 3 5 2 1 7 9 0 2 To extract elements from A, simply use A (row,column). To obtain the element in the second row and third column, do the following. >> A(2,3) ans = 7 You can also extract parts or entire rows and columns with the colon notation. The general form to extract all elements from the ath row to the bth row and the cth column to the dth column is A(a:b,c:d). For a=2, b=3, c=1, & d=2, we get. >> A(2:3,1:2) ans = 2 1 9 0.
Download MATRICES AND VECTORS Tutorials.
0 comments:
Post a Comment