Lab 1

MATLAB Lab 1 Due at 12 noon on Thursday, 5 November 2015 The files below must be in my email inbox by 12 noon. There is no paper submission. For this assignment, there will be an email submission of a .m file and a .pdf file; there will be no paper submission. When you have completed everything, email the files MAT275FirstLastNameLab1.m MAT275FirstLastNameLab1.pdf to your instructor at [email protected] using the subject heading MAT275 First Last Name MATLAB Lab 1. Everywhere throughout, FirstLastName should be replaced with your first and last name without spaces, and First Last Name should be replaced with your first and last name with spaces. A word of caution for those using copy-and-paste, the single quotation mark ’ is different depending on the file format. 1 Welcome To MATLAB This section is designed primarily for those who are new to MATLAB, to become comfortable with the command prompt interface. None of the output from this section will be submitted directly; however, the knowledge gained from Question 1 will be used to complete Question 2 in Section 2 below. MATLAB is installed on most computers on campus. You may be able to download MATLAB to your personal computer from http://myapps.asu.edu or through My Apps in My ASU. You may also be able to use MATLAB via https://citrix.asu.edu. Once the program is successfully installed and opened, you should see the main MATLAB window, which is usually divided up into up to four smaller sub-windows: Command Window, Workspace, Command History, and Current Folder. In the Command Window you should see a command prompt. >> Assign the numbers 5 to the variable a by typing >> a=5 If you want to suppress the output, put a semicolon at the end. If you want to go back to something that you’ve previously typed, use the up arrow key. Use the up arrow key now to go back to the previous entry, and this time add a semicolon to the end to suppress the output. >> a=5; If you want to recall a, you need only type >> a Save the numbers 7 and 11 to the variables b and c by typing >> b=7; c=11; Compute >> b/(a+c) You should get b a+c ˜ 0.4375 . . .. Next, enter the 5 × 3 matrix ? ? ? ? ? ? 2 5 -1 2 -1 12 1 11 2 3 2 -2 2 -2 13 ? ? ? ? ? ? into MATLAB and assign it to the variable A by typing >> A = [2, 5, -1; 2, -1, 12; 1, 11, 2; 3, 2, -2; 2, -2, 13]; Notice that column entries are separated by commas, and rows by semicolons. To save effort, you do not need to use commas to delimit the columns. Use the up arrow key now to go back to the previous entry, and remove the commas >> A = [2 5 -1; 2 -1 12; 1 11 2; 3 2 -2; 2 -2 13]; If you want to recall A, you need only type >> A MATLAB has several predefined matrices. The identity matrix (called eye by MATLAB) has 1’s on the diagonal and 0’s elsewhere. Type >> B = eye(5) If you examine the Workspace window, you will see the MATLAB keeps track of all the variables that you define. A is stored as a 5 × 3 array of double precision floating point numbers, and B is stored as a 5 × 5 array of double precision floating point numbers. We can also access single entries from a matrix. Type >> A(1,2) >> A(3,2) >> A(7,1) for which you should receive the output 5, 11, and “Index exceeds matrix dimensions.” Here are a few more commands. Type >> ones(6,2) >> ones(5) >> 7.*ones(5) >> zeros(7,2) >> zeros(4) >> rand(2,3) >> rand(3) >> 10.*rand(3) >> 2.*rand(3)-ones(3) Note well the .* in the 7.*ones(5), etc. This is to multiply element-wise. Question 1. Find a command that will create an 8 × 5 matrix with random numbers between -2 and 5. Your answer to Question 1 as not submitted directly; however, the knowledge gained from Question 1 will be used to complete Question 2. We can generate arithmetic sequences efficiently using the colon. Type >> p = [1,2,3,4,5,6,7,8] >> q = [1:8] >> r = 1:8 What is the difference between p, q, and r above? Nothing, there are no differences. In the above, we have a default gap of 1 between the numbers in the list 1:8; however, we can specify the gap. For example, to create a gap of 0.1, >> x = [-4:0.1:4] Now that we have created our domain x, we can plot y = sin(x) by >> y = sin(x) >> plot(x,y) 2 Script Files We are going to create a MATLAB script file. Script files are often more convenient than working directly in the Command Window. I will call my script file MAT275ShawnElledgeLab1.m, but you should call yours MAT275FirstLastNameLab1.m using your first and last name without spaces. MATLAB does not allow spaces in file names. After opening MATLAB, there are three tabs at the top: HOME, PLOTS, and APPS. Under the HOME tab, there is a button that says New Script. This will create a new script file, and usually it will also immediately open it in an editor. There are several ways to create a new script file, and this is only one of them. After creating the new script file, it will be titled Untitled, or something similar. Use save as to retitle the file as MAT275FirstLastNameLab1.m, and MATLAB should save it as MAT275FirstLastNameLab1.m in the default directory. A fairly standard default location would be C:\Users\shawn\Documents\MATLAB\MAT275ShawnElledgeLab1.m If you return to the main MATLAB window, the file MAT275FirstLastNameLab1.m should now appear under Current Folder. You may save MAT275FirstLastNameLab1.m elsewhere if you would rather. However, MATLAB will only look in a single folder at a time. So you would need to navigate to this other folder in MATLAB for it to be accessible. The Current Folder window tells you which folder MATLAB is currently using, and MAT275FirstLastNameLab1.m needs to be visible there. Now, open MAT275FirstLastNameLab1.m if it is not already open, and edit the body of the file to be %First Last Name x = [-4:0.1:4]; y = sin(x); plot(x,y); Note that in the first line, anything following the percent sign % has no effect on the code. The percent sign is a comment delimiter. Save your file. There are two ways to execute MAT275FirstLastNameLab1A.m. First, by clicking the big green play button that says Run in the tool bar (which also auto-saves). Second, by returning the Command Window and typing >> MAT275FirstLastNameLab1A (which does not auto-save). Now, edit the body of the script file MAT275FirstLastNameLab1.m to be clear; close; x = [-4:0.1:4]; y = sin(x); plot(x,y,’r’); title(’First Last Name -- y = sin(x)’); xlabel(’x-Axis’); ylabel(’y-Axis’); The close command closes any previously open windows, so your new graph will reappear in a new window. The clear command clears all previously saved variables, clearing out the Workspace. The ’r’ inside of the plot is an option to make the graph red. We are now going to structure your script file MAT275FirstLastNameLab1.m so that you can work with and publish this MATLAB lab in a single document. Edit the body of the script file MAT275FirstLastNameLab1.m to be %First Last Name %% %SECTION 1 clear; A = rand(8,5) %% %SECTION 2 close; clear; x = -4:0.1:4; y = sin(x); plot(x,y,’r’); title(’First Last Name -- y = sin(x)’); xlabel(’x-Axis’); ylabel(’y-Axis’); %% %SECTION 3 %% %SECTION 4 %% %SECTION 5 %% %SECTION 6 %% %SECTION 7 %% %SECTION 8 The double comment delimiter divides the script file into sections, which can be executed separately or together. In the editor window, you should see three tabs at the top: EDITOR, PUBLISH, and VIEW. Under the EDITOR tab, there is a button that says Run, which will run the entire script file. Nearby, there is a button that says Run Section, which will run only the current section of the script file. When you have completed the MATLAB lab, you will publish your code as a .html file by using the Publish button under the PUBLISH tab. The 8 sections in the scrip file correspond to the first 8 sections of this document, each of which has a question specifying what should go into each section. Section 9 of this document contains instructions for how to submit your final solution. Question 2. Adapt your script file MAT275FirstLastNameLab1.m so that the matrix A in SECTION 1 will create a 8 × 5 matrix with random numbers between -2 and 5 as described in Question 1 above. Also, change the color of your sine graph in SECTION 2 to a color of your choosing, that still shows up well (so white would be a bad choice). 3 Drawing Your Initials Edit SECTION 3 of your script file to be close; clear; X = [-0.5 -0.5 -0.8 -1.2 -1.5 -1.5 -0.5 -0.5 -0.8 -1.2 -1.5 -1.5]; Y = [ 1.0 1.2 1.5 1.5 1.2 0.8 -0.8 -1.2 -1.5 -1.5 -1.2 -1.0]; X2 = [1.5 1.5 1.2 0.8 0.5 0.5 1.0 1.1 1.0 0.5 0.5 0.8 1.2 1.5 1.5]; Y2 = [1.0 1.2 1.5 1.5 1.2 0.3 -0.1 0.0 0.1 -0.3 -1.2 -1.5 -1.5 -1.2 -1.0]; hold on plot(X,Y,’Color’,[127/255,1,0],’Linewidth’,2.0); %chartreuse plot(X2,Y2,’Color’,[153/255,50/255,211/255],’Linewidth’,2.0); %dark orchid axis([-2 2 -2 2]) title(’First Last Name’); When you execute this section of code, you should see the initials “SE” appear in a graph window. The first letter is chartreuse, while the second is dark orchid. The way Matlab draws the ‘S’ is by connecting the points whose x and y coordinates are respectively given by the elements in the vectors X and Y . The first number of X is -0.5, and the first number of Y is 1.0; giving the point (-0.5, 1.0). The next point is (-0.5, 1.2), etc. These points are then all connected, creating the ‘S.’ The ‘S’ can then be plotted with the command plot(X,Y). The variation plot(X,Y,’Color’,[127/255,1,0]) changes the color of the plot to the color given by the RGB vector [127/255, 1, 0], which gives chartreuse. The variation plot(X,Y,’Linewidth’,2.0) changes the width of the lines to 2.0, where the default is 0.5. The ‘E’ is given by the vectors X2 and Y 2, and plotted in dark orchid with a line width of 2.0, using plot(X2,Y2,’Color’,[153/255,50/255,211/255],’Linewidth’,2.0). Question 3. Adapt SECTION 3 of your script file so that it draws your own initials in two different colors of your own choice other than chartreuse or dark orchid. If your initials are “SE,” then you should modify it in some way to make it your own. 4 Graph Plotting Techniques Edit SECTION 4 of your script file to be close; clear; a = -4; b = 4; c = -1.5; d = 1.5; DeltaX = 0.5; X = a:DeltaX:b; Y = sin(pi*X); plot(X,Y,’Color’,[1 0 0],’Linewidth’,2.0); axis([a b c d]); title(’First Last Name -- y = sin(pi x)’); This script plots y = sin(px), but it does so with little precision, making it look like a saw-tooth. If you look in the Workspace window, you should see all of the variables. The graph is being plotted over the window [a, b] × [c, d] = {(x, y) ? R 2 : a = x = b and c = y = d}. The variable DeltaX = 0.5 is the step size between the x coordinates. Just as when you drew your initials above, X and Y are respective lists of x and y coordinates; however, this time they are not being created by hand one entry at a time. The command X = a:DeltaX:b creates the vector X to be X = [-4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]. The command Y = sin(pi*X) then makes the vector Y to be the y values corresponding to y = sin(px), Y = [0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1, 0]. Now, edit your code to be close; clear; a = -4; b = 4; c = -1.5; d = 1.5; DeltaX = 0.5; X = a:DeltaX:b; Y = sin(pi*X); plot(X,Y,’Color’,[1 0 0],’Linewidth’,2.0); axis([a b c d]); title(’First Last Name -- y = sin(pi x)’); pause(1); DeltaX2 = 0.125; X2 = a:DeltaX2:b; Y2 = sin(pi*X2); plot(X2,Y2,’Color’,[0 0 1],’Linewidth’,2.0); axis([a b c d]); title(’First Last Name -- y = sin(pi x)’); Now, the script plots y = sin(px) twice: once as the red saw-tooth graph above, and then as a more accurate blue sinusoidal curve; with a dramatic one second pause between the two, thanks to the pause(1). If you would like to see both curves drawn together, then add hold on anywhere before the first plot, and remove the pause(1). The reason the second curve is more accurate is because DeltaX2 = 0.125 is smaller. Now, edit your code to be close; clear; a = -4; b = 4; c = -1.5; d = 1.5; DeltaX = [1.0 0.5 0.25 0.125 0.0625]; for n=1:5 X = a:DeltaX(n):b; Y = sin(pi*X); plot(X,Y,’Linewidth’,2.0); axis([a b c d]); title(’First Last Name -- y = sin(pi x)’); pause(1); end The big difference here is that now we are automating the process using a for-loop. As n = 1, 2, 3, 4, 5 increments, the code within the for-loop is run five times, each time with the incremented n. Instead of defining an individual DeltaX for each plot, now we defined DeltaX to be a vector so that we can index through its members one at a time by calling DeltaX(n). This creates ever more accurate plots of y = sin(px). As before, if you would like to see all the curves drawn together, then add hold on anywhere before the first plot, and remove the pause(1). For fun, if you would like a little color, change plot(X,Y,’Linewidth’,2.0) to plot(X,Y,’Color’,[min(1,floor(2.5-0.5*n)),min(1,0.5*n-0.5),floor(0.2*n)],’Linewidth’,2.0). Question 4. Adapt your code so that it now draws the curve Y = 0.5*X.*cos(pi*X) instead, but keep everything else the same. Note well the .* in the X.*cos(pi*X). This is to multiply the two vectors element-wise. Use the hold on command so that all five plots are drawn together. Feel free to experiment with color as you wish. 5 Direction Fields Download the file dirfield.m from Blackboard. Make sure that you save dirfield.m in your active MATLAB folder, which should make dirfield.m visible in the Current Folder window in your main MATLAB Window. Edit SECTION 5 of your script file to be close; clear; f = @(t,y) 1+t*y; dirfield(f,-2:0.2:2,-2:0.2:2); title(’First Last Name -- Direction Field’); xlabel(’t-Axis’); ylabel(’y-Axis’); Upon execution, this will create the directional field for dy dt = 1 + ty on the window [-2, 2] × [-2, 2] using step sizes 0.2 between the little slope lines. Question 5. Find the directional field for an interesting differential equation of your choice. 6 Recursion Edit SECTION 6 of your script file to be close; clear; a = 1; b = 7; c = -3; d = 4; DeltaX = 0.5; X = a:DeltaX:b; Y = zeros(size(X)); plot(X,Y,’Linewidth’,2.0); axis([a b c d]); title(’First Last Name -- Recursion’); This doesn’t do much. It just plots the curve y = 0 over [1, 7] × [-3, 4]. The gap in the x coordinates is 0.5. We would like to plot the recursion x0 = 1 xn+1 = xn + 0.5 y0 = 1 yn+1 = - xn yn for n = 0, 1, 2, 3, . . . , 12; however, since Matlab starts indexing at 1, it will be convenient to re-index our recursion to x1 = 1 xn+1 = xn + 0.5 y1 = 1 yn+1 = - xn yn for n = 1, 2, 3, . . . , 13. To do so, edit your code to be close; clear; a = 1; b = 7; c = -3; d = 4; DeltaX = 0.5; N = floor((b-a)/DeltaX); X = a:DeltaX:b; Y = zeros(size(X)); Y(1) = 1; for n=1:N Y(n+1) = -X(n)/Y(n); end plot(X,Y,’Linewidth’,2.0); axis([a b c d]); title(’First Last Name -- Recursion’); Note that since the recursion for x is just adding 0.5, all we need to do X = a:DeltaX:b. The y coordinates require a bit more effort. First, we define y1 = 1 outside of the for-loop. Then, we define yn+1 = -xn/yn inside the for-loop as n indexes from 1 to 12, giving y2 through y13. Note that N = floor((b-a)/DeltaX) gives N = 12. This is the number of intervals between 1 and 7 if each segment has width 0.5. If we have N = 12 intervals, then we have 13 endpoints, y1, y2, . . . , y13. Question 6. Adapt your code so that it now plots the recursion x1 = -3 xn+1 = xn + 0.5 y1 = 1 yn+1 = 1 - xn yn + 1 instead. Plot the recursion over the window [-3, 15] × [-15, 50]. Index the recursion over n = 1, 2, 3, . . . , where the indexing ends wherever it needs to so that the last xn is 15; that is, x1 = -3 and xN+1 = 15. Note that the solution is a rather irregular plot. 7 Specific Solutions With ode45 We now return to the direction field of dy dt = 1 + ty, but now we will use the function ode45 to include some specific solutions. We first specify the initial condition of y0 = -1. Edit SECTION 7 of your script file to be close; clear; f = @(t,y) 1+t*y; dirfield(f,-2:0.2:2,-2:0.2:2); title(’First Last Name -- Direction Field’); xlabel(’t-Axis’); ylabel(’y-Axis’); hold on y0 = -1; [ts,ys] = ode45(f,[-2,2],y0); plot(ts,ys); Note that the initial point is (-2, -1), since the initial value of t = -2 is dictated by the [-2, 2] option. The hold is so that MATLAB keeps the old graph around when plotting the new graph, so that they will plot together; otherwise, the new graph would overwrite the old one. A fun way to automate several specific solutions is this close; clear; f = @(t,y) 1+t*y; dirfield(f,-2:0.2:2,-2:0.2:2); title(’First Last Name -- Direction Field’); xlabel(’t-Axis’); ylabel(’y-Axis’); hold on for y0=-2:0.5:2 [ts,ys] = ode45(f,[-2,2],y0); plot(ts,ys); pause(1); end This does the same thing as above, it just picks several y0. The pause(1) creates a timed delay so that they draw one at a time. Question 7. Find the directional field for an interesting differential equation of your choice and automate several specific solutions. 8 Specific Solutions With Euler’s Method Next, we want to approximate solutions for differential equations of the form y 0 = f(x, y) using Euler’s Method. Consider the initial value problem y 0 = y - x 2 - x, y(-2) = 0.75. We’ll start by making the direction field. Ensure that the file dirfield.m is saved in your active MATLAB folder. Edit SECTION 8 of your script file to be close; clear; a = -2; b = 2; c = -2; d = 2; dx = 0.2; dy = 0.2; f = @(x,y) y-x^2-x; %dy/dx = f(x,y) dirfield(f,a:dx:b,c:dy:d); title(’First Last Name -- dy/dx = y-x^2-x’); Note that the variables dx and dy are the width and height of the little red lines in the direction field. We can get a pretty good visual approximation of the solution by editing the code to be close; clear; a = -2; b = 2; c = -2; d = 2; dx = 0.2; dy = 0.2; f = @(x,y) y-x^2-x; %dy/dx = f(x,y) y0 = 0.75; %starting point (a,y0) hold on dirfield(f,a:dx:b,c:dy:d); [xs,ys] = ode45(f,[a,b],y0); plot(xs,ys,’k’,’Linewidth’,2.0); title(’First Last Name -- dy/dx = y-x^2-x’); Our goal is now to use Euler’s Method to create our own approximation of the solution using step sizes ?x = 0.5. Edit your code to be close; clear; a = -2; b = 2; c = -2; d = 2; dx = 0.2; dy = 0.2; f = @(x,y) y-x^2-x; %dy/dx = f(x,y) y0 = 0.75; %starting point (a,y0) DeltaX = 0.5; %Euler step size %N = ??? X = a:DeltaX:b; Y = zeros(size(X)); Y(1) = y0; %for i=1:N % ??? %end hold on dirfield(f,a:dx:b,c:dy:d); [xs,ys] = ode45(f,[a,b],y0); plot(xs,ys,’k’,’Linewidth’,2.0); plot(X,Y,’Linewidth’,2.0); title(’First Last Name -- dy/dx = y-x^2-x’); You’ll notice that there are some pieces missing in the above code. The plot currently include the direction field in red and the ode45 solution in black. However, the blue plot is currently the initialized zero vector Y = zeros(size(X)) together with the initial condition Y(1) = y0, but once you’ve filled in the missing pieces, it will become the Euler approximation. Complete the code so that it now plots the Euler Approximation for the above initial value problem using step sizes of ?x = 0.5. You can update the step sizes to ?x = 0.2 or ?x = 0.05 Question 8. Repeat the above for the initial value problem y 0 = y 2 - x 2 , y(-2) = 1.0, with a step size of ?x = 0.2. 9 How to Submit Your Assignment ¡Congratulations! You’ve completed this MATLAB lab. Now you’re going to publish your .m script file as a .pdf file. In the editor window, you should see three tabs at the top: EDITOR, PUBLISH, and VIEW. Under the PUBLISH tab, there is a button that says Publish. This will (autosave and) run your entire script file, and by default publish your script file as a .html file. This should be saved as MAT275FirstLastNameLab1.html in a new folder called html in your active MATLAB folder. A fairly standard default location would be C:\Users\shawn\Documents\MATLAB\MAT275\html\MAT275ShawnElledgeLab1.html Also, the folder html should now appear under the Current Folder window in your main MATLAB window. While the .html is one of my preferred methods for viewing my own scripts, it is less convenient for email grading since you would have to include all the image files, and I would have to keep track of them. In the editor window, under the PUBLISH tab, directly below the Publish button, there is a down arrow button, which will give you two options. The second option is Edit Publishing Options..., which is what you want. Under Output setting, change the Output file format from html to pdf. If you publish now, you should get a .pdf file, also saved in the html folder in your active MATLAB folder. A fairly standard default location would be C:\Users\shawn\Documents\MATLAB\MAT275\html\MAT275ShawnElledgeLab1.pdf Now that you have both your .m file and .pdf file, email the files MAT275FirstLastNameLab1.m MAT275FirstLastNameLab1.pdf to your instructor at [email protected] using the subject heading MAT275 First Last Name MATLAB Lab 1. There is no paper submission.