Matlab Lab1 PDF

Title Matlab Lab1
Author nflipp84 NA
Course Modern Differential Equations
Institution Arizona State University
Pages 17
File Size 373.7 KB
File Type PDF
Total Downloads 20
Total Views 149

Summary

Modern Differential Equations MAT 275 Shawn Elledge
MATLAB 1...


Description

MATLAB Lab 1 Due at 11:59 pm on Tuesday, 14 February 2017 The files below must be in my email inbox by 11:59 pm. There is no paper submission. Note that part of your grade will be for following the submission instructions precisely. The details can be found in §9 on page 17 below. 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 MAT275LastFirstNameLab1.m MAT275LastFirstNameLab1.pdf to your instructor at [email protected] using the subject heading MAT275 First Last Name MATLAB Lab 1. Everywhere throughout, LastFirstName should be replaced with your last and first name without spaces and in that order, 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, certain character do not copy correctly. E.g., the single quotation mark ’ may not copy correctly, so you may need to edit them by hand.

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 Questions 1A and 2A will be used to complete Questions 1B and 2B 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 the .* in the 7.*ones(5), etc. This is to invoke element-wise multiplication instead of matrix multiplication. Carefully examine what each command does. For some help, you can also type >> help ones >> help zeros >> help rand

Question 1A. (Not Graded.) Find a command that will create an 8 × 5 matrix with random numbers between −2 and 5. Note that you want random numbers, not integers; i.e., do not use randi. Hint: Reread the previous paragraphs about ones and rand. Your answer to Question 1A will not be submitted directly; however, the knowledge gained from Question 1A will be used to complete Question 1B in Section 2 below. 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) with >> y = sin(x) >> plot(x,y)

You should examine the variables x and y in the Workspace window by double-clicking on them. How did MATLAB use x and y to plot the curve? The above sine curve was drawn in a default color; however, either of >> plot(x,y,’r’) >> plot(x,y,’Color’,[1,0,0]) would have drawn it in red. Visit https://www.mathworks.com/help/matlab/ref/colorspec.html, or try googling matlab ColorSpec. Question 2A. (Not graded.) Adapt the above to plot y = cos(x) on the interval [−6, 6], and change the color to one of your choosing, that still shows up well (so white would be a bad choice). Your answer to Question 2A will not be submitted directly; however, the knowledge gained from Question 2A will be used to complete Question 2B in Section 2 below.

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 MAT275ElledgeShawnLab1.m, but you should call yours MAT275LastFirstNameLab1.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 MAT275LastFirstNameLab1.m, and MATLAB should save it as MAT275LastFirstNameLab1.m in the default directory. A fairly standard default location would be C:\Users\shawn\Documents\MATLAB\MAT275ElledgeShawnLab1.m If you return to the main MATLAB window, the file MAT275LastFirstNameLab1.m should now appear under Current Folder. You may save MAT275LastFirstNameLab1.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 MAT275LastFirstNameLab1.m needs to be visible there. Now, open MAT275LastFirstNameLab1.m if it is not already open, and edit the body of the file to be %First Last Name 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’); Note that in the first line, anything following the percent sign % has no effect on the code. The percent sign is a comment delimiter. 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. Save your file. There are two ways to execute MAT275LastFirstNameLab1A.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 >> MAT275LastFirstNameLab1A (which does not auto-save). We are now going to structure your script file MAT275LastFirstNameLab1.m so that you can work with and publish this MATLAB lab in a single document. Edit the body of the script file MAT275LastFirstNameLab1.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 .pdf file by using the Publish button under the PUBLISH tab. The 8 sections in the scrip file correspond to the 8 questions in this document, each of which specifies what should go into each section. Question 1B. Currently, in SECTION 1 of your script file MAT275LastFirstNameLab1.m, the matrix A will create a 8 × 5 matrix with random numbers between 0 and 1. As in Question 1A above, adapt the matrix A to create an 8 × 5 matrix with random numbers between −2 and 5. Note that you want random numbers, not integers; i.e., do not use randi. Question 2B. As in Question 2A above, adapt SECTION 2 your script file to plot y = cos(x) on the interval [−6, 6], and change the color to one 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(πx), 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) ∈ R2 : 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(πx), 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(πx) 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(πx). 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, or else the final project will plot only the last. 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. This is an auxiliary file to construct the dirfield command below. Edit SECTION 5 of your script file to be close; clear; f = @(x,y) 1+x*y; dirfield(f,-2:0.2:2,-2:0.2:2); title(’First Last Name -- Direction Field’); xlabel(’x-Axis’); ylabel(’y-Axis’); Upon execution, this will create the directional field for

dy dx

= 1 + xy 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 xn+1

= 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

=

yn+1

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. Be cautious, there are many details here. Note that the solution is a rather irregular plot.

7

Specific Solutions With ode45

= 1 + xy, but now we will use the function ode45 to include some We now return to the direction field of dy dx specific solutions. We first specify the initial condition of y0 = −1. Edit SECTION 7 of your script file to be close; clear; f = @(x,y) 1+x*y; dirfield(f,-2:0.2:2,-2:0.2:2); title(’First Last Name -- Direction Field’); xlabel(’x-Axis’); ylabel(’y-Axis’); hold on y0 = -1; [xs,ys] = ode45(f,[-2,2],y0); plot(xs,ys);

Note that the initial point is (−2, −1), since the initial value of x = −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 = @(x,y) 1+x*y; dirfield(f,-2:0.2:2,-2:0.2:2); title(’First Last Name -- Direction Field’); xlabel(’x-Axis’); ylabel(’y-Axis’); hold on for y0=-2:0.5:2 [xs,ys] = ode45(f,[-2,2],y0); plot(xs,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, different from the one you chose in Question 5, and then automate several specific solutions, with or without pause(1).

8

Specific Solutions With Euler’s Method

Next, we want to approximate solutions for differential equations of the form y′ = f (x, y) using Euler’s Method. Consider the initial value problem y′ = y − x2 − 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] ...


Similar Free PDFs