Solutions

advertisement
Math 272 - Assignment #1
MATLAB
Solutions
1. Create a vector with the values 3, 6, 9, . . ., 300, and store it in the vector v.
v = 3:3:300
2. Create a vector with the values 22 , 42 , 62 , . . . , 102 , and store it in the vector v.
Three (of many) options are:
v1=2:2:10
v=v1 .^2
v1 = 2:2:10
v = v1 .* v1
v = (2:2:10).^2
3. Create a vector with the values e1 , e2 , e3 , . . . , e20 , and store it in the vector v.
v1 = 1:20
v = exp(v1) % or
v = exp(1:20)
4. Create a vector with the values log10 (1), log10 (2), log10 (3), . . . , log10 (100), and store it in the vector v. Hint: doublecheck that log10 (100) = 2.
x = 1:100;
v = log10(x)
5. Create an 8 × 8 matrix; first 2 columns all ones, last six all zeros
m1 = ones(8, 2);
m2 = zeros(8, 6);
m = [m1, m2]
6. Create a 4 × 20 matrix; first row 1,. . ., 20; second row 2, 4, . . ., 40; third row 3, 6, . . . 60; fourth row 4, 8, . . ., 80.
m = [1:20; 2:2:40; 3:3:60; 4:4:80]
or
v = 1:20;
m = [v*1; v*2; v*3; v*4]
7. Write a loop that displays all multiples of 3 from 12 to 30 (inclusive).
for (i = 12:3:30)
disp(i);
end
8. Use a loop to find the sum of all multiples of 3 from 12 to 30 (inclusive).
1
total = 0;
for (i = 12:3:30)
total = total + i;
end
disp(total);
9. Use the sum command to find the sum of all multiples of 3 from 12 to 30 (inclusive).
v = 12:3:30)
sum(v)
or more directly sum(12:3:30)
Before starting the later questions, you should read either the MATLAB help on “Matrix Indexing”, or the shorter
guide available at
http://www.mathworks.com/company/newsletters/digest/sept01/matrix.html (You only need to read up to, but
not including ’Linear Indexing’ on that page.) There is a link to this on-line guide on the MATH 272 Assignments web
page.
10. Create the vector v = [2 5 9 10 20]
(a) Display the fourth element of the vector.
(b) Display the last element of the vector.
(c) Store the second element of the vector in the new variable x.
(d) Display the subvector made up of the 1st-through-3rd elements of v.
(e) Display the subvector made up of the 1st, 3rd, and 5th elements of v.
v = [2 5 9 10 20]
% a)
v(4)
% displays 4th element
% b)
v(end) % displays last element
% c)
x = v(2) % store 2nd element in x
% d)
v(1:3) % 1st through 3rd elements, or
v([1, 2, 3])
% e)
v([1 3 5]) % 1st, 3rd, 5th elements, or
v(1:2:5)
11. Create the matrix A = magic(4) (a 4×4 ‘magic square’).
(a) Display the element at row 2, column 3.
(b) Display the element in row 4, column 2.
(c) Display the last element in row 3.
(d) Display the entire third row.
(e) Display the entire second column.
2
A = magic(4)
%
16
2
%
5
11
%
9
7
%
4
14
% produces
3
13
10
8
6
12
15
1
% a)
A(2, 3)
% order in indexing is _always_ (row, column)
% b)
A(4, 2)
% element in row 4,
% c)
A(3, 4) %
A(3, end)
col 2
last element in row 3, because there are 4 rows, or
% d)
A(3,:) % entire third row, or
A(3, 1:4) % or
A(3, 1:end)
% e)
A(:, 2) % entire second column, or
A(1:end, 2) % or
A(1:4, 2)
12. Create a smooth-looking graph of the function y = cos(x), x in radians, on the interval [−π, 5π].
x = linspace(-pi, 5*pi);
y = cos(x);
plot(x, y);
Note that using x = -pi:(5*pi) does not create a smooth graph, because too few points are used (x =
−3.14, −2.14, −1.14, . . ., etc.). MATLAB plots points, and not functions, and if you use too few points in a
graph, it looks awful. That is why defining your graphing x coordinates using linspace, which by default uses
100 points which is enough for a smooth-looking graph, is usually better than using the colon operator.
2
13. Create a smooth-looking graph of the function y = e−x , over the interval [−3, 3].
x = linspace(-3, 3);
y = exp(-x.^2);
plot(x, y);
14. Using the min function, and no calculus, estimate the y value of the minimum of the function y = (x − 1)2 (x + 3) + x
on the interval [−2, 3]. Graph the function and zoom in to confirm your answer.
% More sample points gives more detail, so I used 1,000 points with
% linspace
x = linspace(-2, 3, 1000);
y = (x-1).^2 .* (x+3) + x;
plot(x, y);
% Using the zoom function, we can see the minimum at approximately
% (0.868, 0.9354)
min(y) % computes minimum calculated y value
3
15. It is common in scientific plots to draw functions as lines, and plot data as distinct points.
The following points mark the distance between Saturn and several of its moons:
Planet/Object
Mean Distance (AU), d
Period (Earth years), T
Mercury
0.39
0.24
Venus
0.72
0.62
Earth
1
1
Mars
1.52
1.88
Jupiter
5.20
11.86
Saturn
9.54
29.46
Uranus
19.18
84.01
Neptune
30.06
164.8
Pluto
39.44
247.7
The best-fit curve to this data is given by the formula T = d3/2 .
Plot both the raw data (as points) and best fit curve (as a line) on a single graph, and include a legend. The best-fit
graph should look smooth.
d = [0.39, 0.72, 1, 1.52, 5.20, 9.54, 19.18, 30.06, 39.44]
T = [0.24, 0.62, 1, 1.88, 11.86, 29.46, 84.01, 164.8, 247.7]
plot(d, T, ’.’) % or ’+’, or ’*’
hold all
d2 = linspace(min(d), max(d))
T2 = d2.^(1.5)
plot(d2, T2)
hold off;
legend({’Planets’, ’Best Fit’}, ’Location’, ’northwest’)
xlabel(’Distance to Sun (AU)’)
ylabel(’Period (Earth Years)’)
16. When dealing with tables of values, it is often easier to enter them in a spreadsheet like Excel than to enter them in
MATLAB. Fortunately, MATLAB can read Excel files, and then use the resulting data.
Download the Excel file PlanetInfo.xls into the current MATLAB directory: see the “Current Directory” at
the top of the MATLAB interface. Look at the file in Excel, then load the data in it into MATLAB with the command
M = xlsread(’PlanetInfo.xls’)
With the data loaded into the matrix M (9 rows, 2 columns), re-generate the graph from the previous question, including
the legend. You will need to separate the two columns of M for plotting.
M = xlsread(’PlanetInfo.xls’)
d = M(:,1);
T = M(:,2);
% d is all rows, but FIRST column in the Excel data
% T is all rows, but SECOND column in the Excel data
plot(d, T, ’.’) % or ’+’, or ’*’
% alternatively, you can directly plot the two columns against
% each other:
% plot(M(:,1), M(:,2), ’.’)
hold all
d2 = linspace(min(d), max(d))
T2 = d2.^(1.5)
plot(d2, T2)
hold off;
legend({’Planets’, ’Best Fit’}, ’Location’, ’northwest’)
xlabel(’Distance to Sun (AU)’)
ylabel(’Period (Earth Years)’)
4
17. Download the file Marks2013.xlsx and save it in the current MATLAB directory. The columns in the file are, in order,
• Test Grades (/30)
• Exam Grades (/100)
• Final Marks (/100)
Use the xlsread command to read the file into the matrix M.
(a) Plot the test grades vs final grades (1st column, 3rd column). Use the xlabel and ylabel commands to add
appropriate axis labels.
(b) Plot the exam grades vs final grades (2nd column, 3rd column). Use the xlabel and ylabel commands to add
appropriate axis labels.
% Marks analysis
M = xlsread(’Marks2013.xlsx’);
% a) 1st column is Test grades, 3rd is final marks
plot(M(:,1), M(:,3), ’.’);
% or, if you want to separate M and name the individual column vectors,
TestGrades = M(:,1);
FinalGrades = M(:,3);
plot(TestGrades, FinalGrades, ’.’);
% Note: you need the ’.’ in the plot command: you’re plotting points data, and
% without the ’.’, MATLAB tries to plot the points with lines between them.
xlabel(’Test Marks (/30)’);
ylabel(’Final Marks (/100)’);
% b) plot the exam marks vs the final marks
plot(M(:,2), M(:,3), ’.’);
% or, if you want to separate M and name the individual column vectors,
ExamGrades = M(:,2);
FinalGrades = M(:,3);
plot(ExamGrades, FinalGrades, ’.’);
xlabel(’Exam Marks (/100)’);
ylabel(’Final Marks (/100)’);
5
Download