VECTORS IN MATLAB
Matlab is a software package that makes it easier for you to enter matrices and vectors, and manipulate them. The interface follows a language that is designed to look a lot like the notation use in linear algebra. In the following tutorial, we will discuss some of the basics of working with vectors.Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by placing a sequence of numbers within square braces:
>> v = [3 1] v = 3 1This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second entry is a 1. Note that matlab printed out a copy of the vector after you hit the enter key. If you do not want to print out the result put a semi-colon at the end of the line:
>> v = [3 1]; >>If you want to view the vector just type its label:
>> v v = 3 1You can define a vector of any size in this manner:
>> v = [3 1 7 -21 5 6] v = 3 1 7 -21 5 6Notice, though, that this always creates a row vector. If you want to create a column vector you need to take the transpose of a row vector. The transpose is defined using an apostrophe ("'"):
>> v = [3 1 7 -21 5 6]' v = 3 1 7 -21 5 6A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define a set of numbers with a common increment using colons. For example, to define a vector whose first entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:
>> v = = [1:8] v = 1 2 3 4 5 6 7 8If you wish to use an increment other than one that you have to define the start number, the value of the increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with steps of .25 you enter the following:
>> v = [2:.25:4] v = Columns 1 through 7 2.0000 2.2500 2.5000 2.7500 3.0000 3.2500 3.5000 Columns 8 through 9 3.7500 4.0000
Accessing elements within a vector
You can view individual entries in this vector. For example to view the first entry just type in the following:>> v(1) ans = 2This command prints out entry 1 in the vector. Also notice that a new variable called ans has been created. Any time you perform an action that does not include an assignment matlab will put the label anson the result.
To simplify the creation of large vectors, you can define a vector by specifying the first entry, an increment, and the last entry. Matlab will automatically figure out how many entries you need and their values. For example, to create a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:
>> 0:2:8 ans = 0 2 4 6 8Matlab also keeps track of the last result. In the previous example, a variable "ans" is created. To look at the transpose of the previous result, enter the following:
>> ans' ans = 0 2 4 6 8To be able to keep track of the vectors you create, you can give them names. For example, a row vector v can be created:
>> v = [0:2:8] v = 0 2 4 6 8 >> v v = 0 2 4 6 8 >> v; >> v' ans = 0 2 4 6 8Note that in the previous example, if you end the line with a semi-colon, the result is not displayed. This will come in handy later when you want to use Matlab to work with very large systems of equations.
Matlab will allow you to look at specific parts of the vector. If you want to only look at the first three entries in a vector you can use the same notation you used to create the vector:
>> v(1:3) ans = 0 2 4 >> v(1:2:4) ans = 0 4 >> v(1:2:4)' ans = 0 4
Basic operations on vectors
Once you master the notation you are free to perform other operations:>> v(1:3)-v(2:4) ans = -2 -2 -2For the most part Matlab follows the standard notation used in linear algebra. We will see later that there are some extensions to make some operations easier. For now, though, both addition subtraction are defined in the standard way. For example, to define a new vector with the numbers from 0 to -4 in steps of -1 we do the following:
>> u = [0:-1:4] u = [0:-1:-4] u = 0 -1 -2 -3 -4We can now add u and v together in the standard way:
>> u+v ans = 0 1 2 3 4Additionally, scalar multiplication is defined in the standard way. Also note that scalar division is defined in a way that is consistent with scalar multiplication:
>> -2*u ans = 0 2 4 6 8 >> v/3 ans = 0 0.6667 1.3333 2.0000 2.6667With these definitions linear combinations of vectors can be easily defined and the basic operations combined:
>> -2*u+v/3 ans = 0 2.6667 5.3333 8.0000 10.6667You will need to be careful. These operations can only be carried out when the dimensions of the vectors allow it. You will likely get used to seeing the following error message which follows from adding two vectors whose dimensions are different:
>> u+v' ??? Error using ==> plus Matrix dimensions must agree.
Matrices in Matlab
Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of row vectors (note that the spaces are required!):>> A = [ 1 2 3; 3 4 5; 6 7 8] A = 1 2 3 3 4 5 6 7 8You can also treat it like a row of column vectors:>> B = [ [1 2 3]' [2 4 7]' [3 5 8]'] B = 1 2 3 2 4 5 3 7 8(Again, it is important to include the spaces.) If you have been putting in variables through this and the tutorial on vectors, then you probably have a lot of variables defined. If you lose track of what variables you have defined, the whos command will let you know all of the variables you have in your work space.>> whos Name Size Bytes Class A 3x3 72 double array B 3x3 72 double array v 1x5 40 double array Grand total is 23 elements using 184 bytesWe assume that you are doing this tutorial after completing the previous tutorial. The vector v was defined in the previous tutorial. As mentioned before, the notation used by Matlab is the standard linear algebra notation you should have seen before. Matrix-vector multiplication can be easily done. You have to be careful, though, your matrices and vectors have to have the right size!>> v = [0:2:8] v = 0 2 4 6 8 >> A*v(1:3) ??? Error using ==> * Inner matrix dimensions must agree. >> A*v(1:3)' ans = 16 28 46Get used to seeing that particular error message! Once you start throwing matrices and vectors around, it is easy to forget the sizes of the things you have created. You can work with different parts of a matrix, just as you can with vectors. Again, you have to be careful to make sure that the operation is legal.>> A(1:2,3:4) ??? Index exceeds matrix dimensions. >> A(1:2,2:3) ans = 2 3 4 5 >> A(1:2,2:3)' ans = 2 4 3 5Matrix Functions
Once you are able to create and manipulate a matrix, you can perform many standard operations on it. For example, you can find the inverse of a matrix. You must be careful, however, since the operations are numerical manipulations done on digital computers. In the example, the matrix A is not a full matrix, but matlab's inverse routine will still return a matrix.>> inv(A) Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.565062e-18 ans = 1.0e+15 * -2.7022 4.5036 -1.8014 5.4043 -9.0072 3.6029 -2.7022 4.5036 -1.8014By the way, Matlab is case sensitive. This is another potential source of problems when you start building complicated algorithms.>> inv(a) ??? Undefined function or variable a.Other operations include finding an approximation to the eigen values of a matrix. There are two versions of this routine, one just finds the eigen values, the other finds both the eigen values and the eigen vectors. If you forget which one is which, you can get more information by typing help eig at the matlab prompt.>> eig(A) ans = 14.0664 -1.0664 0.0000 >> [v,e] = eig(A) v = -0.2656 0.7444 -0.4082 -0.4912 0.1907 0.8165 -0.8295 -0.6399 -0.4082 e = 14.0664 0 0 0 -1.0664 0 0 0 0.0000 >> diag(e) ans = 14.0664 -1.0664 0.0000Matrix Operations
There are also routines that let you find solutions to equations. For example, if Ax=b and you want to find x, a slow way to find x is to simply invert A and perform a left multiply on both sides (more on that later). It turns out that there are more efficient and more stable methods to do this (L/U decomposition with pivoting, for example). Matlab has special commands that will do this for you. Before finding the approximations to linear systems, it is important to remember that if A and B are both matrices, then AB is not necessarily equal to BA. To distinguish the difference between solving systems that have a right or left multiply, Matlab uses two different operators, "/" and "\". Examples of their use are given below. It is left as an exercise for you to figure out which one is doing what.>> v = [1 3 5]' v = 1 3 5 >> x = A\v Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.565062e-18 x = 1.0e+15 * 1.8014 -3.6029 1.8014 >> x = B\v x = 2 1 -1 >> B*x ans = 1 3 5 >> x1 = v'/B x1 = 4.0000 -3.0000 1.0000 >> x1*B ans = 1.0000 3.0000 5.0000Plots:
It is also easy to create plots in MATLAB.
y = f(x), and then plot the set points (xi, yi). By default matlab draws a straight line connecting neighboring points, The basic method for plotting a function f(x) in matlab is to create an array of x values, calculate a second array while the points themselves are invisible.
x1 = [0:0.25:4*pi]; % creates an array from 0 to 4*pi with a spacing of 0.25 x2 = linspace(0,4*pi,1000); % creates an array from 0 to 4*pi with 1000 evenly spaced points y1 = 5*sin(x1).*cos(x1).^2; % calculate y = f(x) y2 = 5*sin(x2).*cos(x2).^2; % note the use of the element-by-element operations .* .^ ./ plot(x1,y1); hold on; plot(x2,y2,’color’,’g’,’LineStyle’,’--’),’LineWidth’,2); hold off;
POLYNOMIALS
In MATLAB, a polynomial is represented by a vector. To create a polynomial in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:To enter this into MATLAB, just enter it as a vector in the following manner x = [1 3 -15 -2 9] x = 1 3 -15 -2 9MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,would be represented in MATLAB as: y = [1 0 0 0 1]You can find the value of a polynomial using the polyval function. For example, to find the value of the above polynomial at s=2,z = polyval([1 0 0 0 1],2) z = 17You can also extract the roots of a polynomial. This is useful when you have a high-order polynomial such asFinding the roots would be as easy as entering the following command; roots([1 3 -15 -2 9]) ans = -5.5745 2.5836 -0.7951 0.7860Let's say you want to multiply two polynomials together. The product of two polynomials is found by taking the convolution of their coefficients. MATLAB's function conv that will do this for you.x = [1 2]; y = [1 4 8]; z = conv(x,y) z = 1 6 16 16Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let's divide z by y and see if we get x.[xx, R] = deconv(z,y) xx = 1 2 R = 0 0 0 0As you can see, this is just the polynomial/vector x from before. If y had not gone into z evenly, the remainder vector would have been something other than zero.
LOOPS
In this tutorial we will demonstrate how the for and the while loop are used. First, the for loop is discussed with examples for row operations on matrices and for Euler's Method to approximate an ODE. Following the for loop, a demonstration of the while loop is given.
For Loops
The for loop allows us to repeat certain commands. If you want to repeat some action in a predetermined way, you can use the for loop. All of the loop structures in matlab are started with a keyword such as "for", or "while" and they all end with the word "end". Another deep thought, eh. The for loop is written around some set of statements, and you must tell Matlab where to start and where to end. Basically, you give a vector in the "for" statement, and Matlab will loop through for each value in the vector: For example, a simple loop will go around four times each time changing a loop variable, j:>> for j=1:4, j end j = 1 j = 2 j = 3 j = 4 >>When Matlab reads the "for" statement it constructs a vector, [1:4], and j will take on each value within the vector in order. Once Matlab reads the "end" statement, it will execute and repeat the loop. Each time the for statement will update the value of j and repeat the statements within the loop. In this example it will print out the value of j each time. For another example, we define a vector and later change the entries. Here we step though and change each individual entry:>> v = [1:3:10] v = 1 4 7 10 >> for j=1:4, v(j) = j; end >> v v = 1 2 3 4Note, that this is a simple example and is a nice demonstration to show you how a for loop works.
A better example, is one in which we want to perform operations on the rows of a matrix. If you want to start at the second row of a matrix and subtract the previous row of the matrix and then repeat this operation on the following rows, a for loop can do this in short order:>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']
A =
1 3 2
2 2 1
3 1 3
>> B = A;
>> for j=2:3,
A(j,:) = A(j,:) - A(j-1,:)
end
A =
1 3 2
1 -1 -1
3 1 3
A =
1 3 2
1 -1 -1
2 2 4
For a more realistic example, since we can now use loops and perform row operations on a matrix, Gaussian Elimination can be performed using only two loops and one statement:>> for j=2:3,
for i=j:3,
B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)
end
end
B =
1 3 2
0 -4 -3
3 1 3
B =
1 3 2
0 -4 -3
0 -8 -3
B =
1 3 2
0 -4 -3
0 0 3
Another example where loops come in handy is the approximation of differential equations. The following example approximates the D.E. y'=x^2-y^2, y(0)=1, using Euler's Method. First, the step size, h, is defined. Once done, the grid points are found, and an approximation is found. The approximation is simply a vector, y, in which the entry y(j) is the approximation at x(j).>> h = 0.1;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> size(x)
ans =
1 21
>> for i=2:21,
y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
end
>> plot(x,y)
>> plot(x,y,'go')
>> plot(x,y,'go',x,y)
While Loops
If you don't like the for loop, you can also use a while loop. The while loop repeats a sequence of commands as long as some condition is met. This can make for a more efficient algorithm. In the previous example the number of time steps to make may be much larger than 20. In such a case the for loop can use up a lot of memory just creating the vector used for the index. A better way of implementing the algorithm is to repeat the same operations but only as long as the number of steps taken is below some threshold. In this example the D.E. y'=x-|y|, y(0)=1, is approximated using Euler's Method:>> h = 0.001;
>> x = [0:h:2];
>> y = 0*x;
>> y(1) = 1;
>> i = 1;
>> size(x)
ans =
1 2001
>> max(size(x))
ans =
2001
>> while(i<max(size(x)))
y(i+1) = y(i) + h*(x(i)-abs(y(i)));
i = i + 1;
end
>> plot(x,y,'go')
No comments:
Post a Comment