MATLAB Workbook: Vector Calculus For Engineers
MATLAB Workbook: Vector Calculus For Engineers
CME100
Vector Calculus for Engineers
Second Edition
Authors:
Perrine Pepiot
Vadim Khayms
Table of Contents
1. Saving Workspace
2. Defining scalar variables
3. Vector operations
(1)
4. Vector operations
(2)
5. Vector operations
(3)
6. Plots in 1 - D
7. How to use a script
8. If elseif else statements
9. For loops
10. While loops
11. More programming examples: car motion
12. More programming examples: electric circuit
13. More programming examples: Newtons method
14. Surfaces in 3 D
15. Gradient
16. Motion of a particle
17. Level curves
18. Finding local minima of a function
19. Fitting data
20. Vectors of random numbers
21. More random numbers
22. Performing numerical integration
23. Computing work done by a force along a path
Getting started
1. Saving Workspace
Commands :
diary
diary(filename)
diary off
The diary command allows saving all command window inputs and outputs (except graphics)
in a separate file, which can be opened with most text editors (e.g. Microsoft Word) and
printed.
Start the diary and save the file as mydiary. Compute the number of seconds in one year.
Close the diary. Open the file mydiary using any text editor.
SOLUTION
In the Command Window :
In Microsoft Word :
>> diary(mydiary)
60*60*24*365
>> 60*60*24*365
ans =
ans =
31536000
31536000
diary off
Hint :
MATLAB workspace will be saved into a file named diary when no file name is specified.
Hint:
If you need help with a specific MATLAB command, simply type help command name in the command
window. Detailed information will be displayed with everything needed to use this command properly.
If you dont know the exact name of the command, type lookfor keyword, which returns all the
commands related to that keyword.
YOUR TURN
Start a new diary and call it newdiary. Compute the product of all the integers from 1 to 9.
Close the diary. Open it with a text editor and print it.
+ - / * ^ ;
clear
%
MATLAB can be used as a calculator and can store the inputs or the outputs into variables. If
a semicolon ; is placed at the end of a statement, the value of the variable is calculated but
not displayed on the screen. To clear variables from the workspace, use the command clear.
SOLUTION
>> % Define a
>> a = 2
>> c = a + 2 * b ;
a=
>> % Display c
>> c
>> % Define b
c=
12
>> b = 5
b=
>> clear
>> % Compute c
>> c
>> c = a + b^2
c=
27
Hint: To display the current value of a variable, double-click on its name in the command window.
Hint: To avoid retyping previously used command, use up and down arrows
YOUR TURN
Set variable a to 12345679, variable b to 9, and assign your favorite number between 1 and 9
to c. Compute the product abc and display it on the screen. Clear all variables at the end.
3. Vector operations ( 1 )
Commands:
x0 and x1
x0 : x : x1
by x
PART 1
Create the vector V 1 2 3. Display each of the elements. Multiply the first and second
elements. Change the third element to 4 and display the new vector on the screen.
SOLUTION
>> V = [1 2 3]
>> V (2)
V=
1
ans =
2
>> V (1)
ans =
1
>> V (3)
ans =
>> V (3) = 4
V=
x=
YOUR TURN
a)
b) Replace the third element of your vector by the sum of the first and second elements.
PART 2
Additional more convenient ways to create arrays with equally spaced elements are illustrated
below:
>> V = linspace ( 0 , 10 , 6 )
>> W = 0 : 2 : 10
V=
W=
0
10
10
YOUR TURN
c)
Hint: You can check the dimension of an array in the command window using the size command.
4. Vector operations ( 2 )
Commands :
.* ./ .^
SOLUTION
>> % Define x and y
z=
4
-2
-3
>> z = x . * y
ans =
Hint:
25
A period is needed for element-by-element operations with arrays in front of *, / , and ^ . A period
is NOT needed in front of + and - .
YOUR TURN
Divide y by x element by element. Display the result.
5. Vector operations ( 3 )
Evaluate the function y given below between x 0 and x :
y e x sin 2 x
x2
3
To do so, first create a vector x containing equally spaced elements in the domain of the
function. Then compute the corresponding vector y. Each element of y will be equal to the
value of the function evaluated at the corresponding elements of x.
SOLUTION
>> x = 0 : 0.1 : pi;
>> y = sin(2*x) . * exp(x) + x .^ 2 / 3
y=
Columns 1 through 9
0
0.2229
0.4890
0.7922
1.1235
1.4707
1.8183
2.1478
2.4379
Columns 28 through 32
-9.0685 -7.7676 -5.6404 -2.6122
1.3589
YOUR TURN
Compute the value of the following function of x between 1 and 3, using equally spaced points separated by
0.2:
1
y x cos x 2 3
x
6. Plots in 1 - D
Commands :
plot
title
xlabel, ylabel
legend
hold on / hold off
subplot
The displacement of an object falling under the force of gravity is given by:
1 2
gt
2
where g is the acceleration of gravity [m/s2], y is the distance traveled [m], and t is time [s].
The following table gives the values of g for three different planets:
Planet
Earth
Jupiter
PART 1
Mercury
g
9.80
m/s2
24.79
m/s2
3.72
m/s2
Plot the distance fallen as a function of time near the surface of the Earth between 0 and 10
seconds, with an increment of 1 second. Add a title and x and y labels.
SOLUTION
>> % Define time values
>> t = 0:1:10;
Distance fallen as a function of time on Earth
1000
900
>> g = 9.80;
800
>> % Plot
>> plot(t,y,'b--')
700
Distance fallen [m]
>> y = g * t.^2;
600
500
400
300
200
100
5
Time [s]
Earth')
Hint: You can define the color and the style of a curve when using the plot command. In the
example below, b- - stands for blue dashed line. Other possible options are : for a dotted
line, -. for a dash-dotted line, - for a solid line. The colors are designated by the first letter
of the desired color (b,r,g,y k = black). If the style or the color is not specified, MATLAB
uses its default settings. See help plot for additional information.
Hint: You can zoom in and out, draw arrows, add titles, labels, legends, or write text directly
in the figure using the menu bar.
YOUR TURN
10
PART 2
Multiple functions can be plotted on the same figure using the hold on and hold off
commands. Plot the displacement curve for both the Earth and Jupiter in the same figure and
add a legend.
SOLUTION
>> % Compute displacement for Earth
>> g = 9.80;
>> t = 0:1:10;
>> legend('Earth','Jupiter')
>> y = g * t.^2;
>> % End of the hold command
>> % Plot displacement for Earth
>> plot(t,y,'b--')
>> grid on
>> hold on
2000
1500
1000
500
5
Time [s]
10
YOUR TURN
Plot all three curves for the three planets in the same figure. Use different styles for each of
the planets and include a legend
PART 3
The three curves can also be plotted on the same figure in three different plots using the
subplot command. Plot the curves for Earth and Jupiter using subplot.
SOLUTION
>> % Compute displacement for Earth
>> t = 0:1:10;
>> % Plot
>> g = 9.80;
>> y = g*t.^2;
>> grid on
Earth')
1000
800
600
400
200
0
>> g=24.79;
3
4
5
6
7
8
Time [s]
Distance fallen as a function of time on Jupiter
10
10
>> y = g*t.^2;
>> % Plot
>> subplot(2,1,2)
>> plot(t,y,'r-')
>> xlabel('Time [s]')
>> ylabel('Distance fallen [m]')
2500
2000
1500
1000
500
0
5
Time [s]
YOUR TURN
Using subplot, create three different displacement plots in the same window corresponding to each of the
three planets.
Programming
7. How to use a script
Commands :
clear
close
SOLUTION
Open new .m file
Type commands
nice plot
15
% Plotting y
plot ( x , y )
grid on
title ( nice plot )
xlabel ( x )
ylabel ( y )
10
-5
-10
-15
10
15
>> niceplot
Hint: It is a good idea to always start your script with a clear command. This will help eliminate a lot of
unexpected errors associated with using previously computed values when you execute the script
multiple times
Hint:
To insert comments within a script, start each line with a % symbol. The comments will appear
green.
Hint: If you type help niceplot in the command window, the comments contained at the beginning of the
file will be displayed. This is how all help information is stored and displayed for existing
MATLAB functions
YOUR TURN
Modify the above script by adding a second curve to the same plot: y x cos x . Use
different styles for the two functions. Add a legend.
if
elseif
condition
statement
condition
statement
else
statement
end
a)
Suppose you are buying apples at a supermarket. If you buy more than 5 apples, you get a 10%
discount. Write a program computing the amount owed given the price per apple (assume it to be $1)
and the number of apples bought.
b) Suppose now the store offers a super discount of 40% if you buy more than 20 apples. Modify the code
in part a) to implement this new condition using the elseif statement.
SOLUTION
a)
n = 21;
n = 6;
price = 1;
price = 1;
if n >= 5
elseif
else
n >= 20
cost = 60/100 * price * n;
else
cost = price * n;
end
cost = price * n;
end
>> apple
cost =
>> apple
cost =
5.4000
12.6000
b)
YOUR TURN
If you really love apples, you can purchase a pre-packaged box with 30 apples for $15.
Modify the code above to include this offer. Test your code for each of the following cases: n
= 3, 11, 22 and 30. For each n, compute the cost by hand and then compare it to the result
obtained by running your script.
9. For loops
Command :
a)
Compute 10!, i.e. the product of all the integers from 1 to 10.
Define the following piecewise function between x 3 and x 5 using 1000 points and plot it.
y x x
y x sin x
y x ln x
x0
0 x 1
x 1
SOLUTION
a)
In a script called part a:
% Initialization
result = 1;
result =
3628800
b)
In a script called part b:
In the command window :
% Initialization
result = 0;
>> part2
result =
2551
plot(x,y)
% Define vector x
x = linspace(-3,5,1000);
% Test each value of x and compute the
1.5
1
for i = 1:length(x)
0.5
if x(i) < 0
0
y
y(i) = x(i);
elseif x(i)>1
-0.5
-1
y(i) = log(x(i));
-1.5
else
y(i) = sin (pi * x(i));
-2
end
-2.5
-3
-3
end
-2
-1
1
x
% Plot y as a function of x
YOUR TURN
a) Write a script to compute the sum of all components of a vector. Your script should work regardless of
the size of the vector. Test your script with using the following vector: V 2 1.1 3 5.2 4.7.
b) Define and plot the function y x x for x ranging between 1 and 1, with x coordinates spaced by
0.05.
abs (x)
sqrt (x)
while condition
statement
end
returns the absolute value of x
returns the square root of x
1
a
x is generally
2
x
a better approximation. For example, with a = 2, starting with x = 1, we obtain the following
3 17 577
successive approximations: 1, ,
,
... approaching in the limit the true value of
2 12 408
2 1.4142135
Using the above formula, write a script to compute iteratively the value of
compare your solution to the exact value of
10 . At each step,
between your solution and the exact one is less than 10 4 . Start the iteration with the initial
guess x = 1. Plot the absolute value of the error versus the current iteration number.
SOLUTION
% Value of a
a = 10;
% First guess for the square root of a
x(1) = 1;
2.5
i = 1;
2
1.5
error
i = i + 1;
x ( i ) = 1/2 * (x (i-1) + a / x (i-1));
end
x(i)
plot ( abs ( x-sqrt(10) ) )
grid on
1.5
2.5
3
3.5
4
Number of iterations
4.5
5.5
YOUR TURN
a) In the above algorithm, x is a vector containing all the successive approximations of 10 . We are
usually interested only in the final result and dont need to store each intermediate step. Modify the
above script so that x is now a scalar iterate that overwrites the previous one. Compute 11 to an error
of less than 10 4 , starting with x = 1.
b) Using the modified code, determine how many iterations are necessary to reach the required accuracy?
[Hint: add a counter whose value is incremented by one each time you perform an iteration]
dv
F
dt
(1)
This equation determines the velocity of the car as a function of time. To obtain the position
of the car, we use the following kinematic relation:
dx
v
dt
(2)
Although this problem can be solved analytically, in this exercise we would like to come up
with a numerical solution using MATLAB. We first need to discretize the equations, i.e.
evaluate the position and velocity at equally spaced discrete points in time, since MATLAB
doesnt know how to interpret continuous functions. The solution for vt and xt will then
be represented by vectors containing the values of the velocity and the position of the car
respectively at these discrete points in time separated by t .
The time derivative for the velocity in (1) can be approximated by:
dv v t t v t
dt
t
Equation (1) then becomes:
v t t vt F
t
m
vt t vt t
vn 1 vn t
vn 1 .
xt t xt
vt
t
F
m
F
, where the unknown is
m
x t t xt t v t
xn 1 xn t vn
Solve the above equations for position and velocity and plot the position as a function of time.
Display the distance traveled and the time it takes to reach 50 km/h.
SOLUTION
% Force applied to the car in Newtons
F = 2000;
% Mass of the car in kg
m = 900;
% Time step in seconds
deltat = 0.1
% Initialization: at t=0, the car is at rest
t(1) = 0;
v(1) = 0;
x(1) = 0;
n = 1;
% Iterate until the velocity reaches 50 km/h =
13.89 m/s. For that, we need a WHILE loop
which tests the value of the velocity at each step.
If it's greater than 13.89 m/s, we exit the loop.
% Advance time
t(n+1) = t(n) + deltat;
45
40
35
30
position [m]
25
20
15
end
10
5
0
4
time [s]
YOUR TURN
When the speed of the car reaches 50 km/h, it stops accelerating and begins to slow down. At
the beginning, the brakes are applied slowly, and as the time increases, the braking force
increases. The breaking force exerted on the car can be modeled as follows:
Fbreak 100 t v 2 in Newtons, with t in seconds. The equations of motion become:
m
dv
Fbreak 100tv 2 and
dt
dx
v
dt
100
t n v 2 n
m
and
xn 1 xn t vn
The goal of this exercise is to compute the distance driven and the time needed for the car to
slow down from 50 km/h to 10 km/h.
a) Write a script to solve these equations numerically. Choose zero for both the initial position and time
and 13.89 m/s for the initial velocity. Use the same time step as in the above example. Stop the iteration
when the velocity reaches 2.78 m/s (10 km/h).
b) Plot the position and velocity as a function of time in the same figure, using subplot. Add a title, labels,
and a grid.
c)
Determine the time and the distance traveled to slow down to 10 km/h.
Given the input voltage V t , write a script that computes the output current I t . Test your
code for the following input:
V t 3 3 sin t for t 0
Use the time step t 0.1 . Plot V t and I t on the same set of axes for t ranging between
0 and 2 seconds.
SOLUTION
clear
plot(t,V,'-',t,I,'b-.')
close
xlabel('Time')
legend('Input Voltage','Output Intensity')
t = 0:0.1:2*pi;
V = 3+3*sin(3*t);
Input Voltage
Output Intensity
10
% current output
for i=1:length(V)
if V(i)<1
I(i) = 10;
I(i) = -9/4*V(i)+49/4;
else
I(i) = 1;
end
1
end
Time
YOUR TURN
A physical circuit does not respond instantaneously. Suppose there is a delay of 0.3 seconds
(3 time steps) between the input and the output, i.e. the current I at time t corresponds to the
voltage V at time t -3t ).
Modify the code above to include this delay. If the current is undefined at a certain time, assume it to
be zero. Plot V and I on the same set of axes. Use different styles. Add a grid, a title, and a legend.
qVdiode
I diode I s e kT 1
1.8
1.6
1.4
where
I s 0.07 pA 7.1014 A
kT
26mA at 300K
q
Current [A]
a)
1.2
1
0.8
0.6
0.4
0.2
0
0.1
0.2
0.3
0.4
0.5
0.6
Voltage [V]
0.7
0.8
0.9
R
=
20
SOLUTION
Using Kirschoffs voltage law: E0 Vdiode RI
We can substitute the current I by its expression as a function of Vdiode using the given by the
I-V characteristic:
qVdiode
qVdiode
E0 Vdiode RI s e kT 1 or E0 Vdiode RI s e kT 1 0
As a result we obtain an equation for Vdiode of the form f Vdiode 0 , which can be solved
using the Newtons method. The current is then obtained using the diode I-V characteristic
giving the current in the circuit as a function of Vdiode .
The algorithm is quite simple: starting from an initial guess V0 , a better approximation of
V is obtained from the following expression:
V1 V0
or, in general: Vn 1 Vn
f Vn
f
Vn
f V0
f
V0
q
e
kT
qVdiode
kT
Perform several iterations of the Newtons method using the for loop. Find the diode voltage
and the current in the circuit using 20 iterations.
In a script:
C = 0.026;
clear
% Input voltage
% Iterations
Is = 7*10^-14;
% Value of Is
for i = 1:20
R = 200;
% Value of KT/q
Vdiode
Vdiode
I = Is*(exp( Vdiode/C ) - 1)
>> newton
Vdiode =
% Display solution
I=
0.6718
% Vdiode
0.0116
YOUR TURN
A for loop was used in the above script to perform the Newtons iteration. The iteration was
terminated after a specified number of loops. In this case, we have performed a certain
number of iterations without concerning ourselves with the accuracy of the computed
solution. A more efficient approach would be to test for convergence and stop the iteration
when the required level of accuracy has been achieved. This can be done using a while loop.
The convergence criterion often used is the difference between the solutions obtained in two
successive iterations. The loop is terminated when the difference is below a specified
threshold value.
a)
Rewrite the above script using a while loop. Terminate the iteration when the absolute value of the
difference between any two successive iterates for Vdiode is less than 10-6.
Note: youll have to store the old value of Vdiode before computing the new one.
b)
14. Surfaces in 3 D
Command :
surface
meshgrid
Create a two-dimensional grid of coordinate values
Create a 3D surface on the domain defined by meshgrid
shading (interp) Interpolate colormap
colorbar
Add a colorbar
sin x 2 y 2
16
Note: The 10 16 in the denominator is needed to avoid division by zero when x y 0 and
to get the correct value in the limit:
SOLUTION
lim
x 0
y 0
sin x 2 y 2
x y
2
Nice 3D plot
clear
close all
0.8
[x,y] = meshgrid(-3:0.1:3,-4:0.1:4);
1
0.8
z = sin(x.^2+y.^2)./(x.^2+y.^2+10^-16);
0.6
0.6
surface(x,y,z)
0.4
0.4
0.2
0.2
grid on
shading('interp')
-0.2
xlabel('x')
2
-0.4
-3
ylabel('y')
-2
zlabel('z')
-1
-2
1
title('Nice 3D plot')
-4
colorbar
YOUR TURN
Plot the function
sin x
z x, y
x 1016
sin y
16
y 10
for x and y both ranging between and . Use an increment of 0.1. Do not use the shading
option. Add labels and a title. Note: the plot you obtain represents a diffraction pattern
produced by a small rectangular aperture illuminated by a monochromatic light beam. The
function z represents the intensity of the light behind the aperture.
Hint: You can change the limits by selecting the arrow in the figure menu and double-clicking the figure itself.
A window will appear in which you can modify the key parameters. Try to re-define the limits on z to go from 0
to 0.1 to better resolve surface features.
15. Gradient
Commands :
gradient
Find the derivative of the following function: y xe x for x ranging between 0 and 1, with an increment of
0.1. Plot both the analytical and the numerical derivatives in the same figure.
SOLUTION
clear
close
x=0:0.5:10;
y=x.*exp(-x);
derY = gradient(y,0.5);
derYex = (1 - x).*exp(-x);
-0.2
y
plot(x,derY,'-')
hold on
plot(x,derYex,':')
0.8
0.6
y
grid on
title('derivative of the function y = xe^{-x}')
legend('numerical derivative','exact derivative')
xlabel('x')
ylabel('y')
0.4
0.2
-0.2
5
x
10
Hint: The spacing between points corresponds to the difference between the adjacent elements of vector x.
YOUR TURN
a)
b) Using the gradient function, compute the derivative of the function in a) for x ranging between 0 and 1,
with an increment of 0.1. Plot the analytical and the numerical derivatives in the same figure.
plot3
Plot a curve in 3D
The motion of a particle in three dimensions is given by the following parametric equations:
x t cos t
y t 2sin t
z t 0
a)
for
0 t 2
b) compute the velocity components Vx , Vy and the magnitude of the velocity vector
c)
vector
clear
compute the angle between the velocity vector and the acceleration vector
dt = 0.1;
t = 0:dt:2*pi;
% time vector
% x, y and z vectors
d)
x = cos(t);
y = 2*sin(t);
components
z = 0*t;
% Tx = Vx/|V|
Tx = Vx./speed;
% Ty = Vy/|V|
a)
% plot trajectory in 3D
Ty = Vy./speed;
e)
plot3(x,y,z)
grid on
xlabel('x')
ylabel('y')
% cos(theta) = V.A/(|V||A|)
zlabel('z')
theta =
acos((Vx.*Ax+Vy.*Ay)./speed./acceleration);
b)
% Computation of the velocity components
% Vx = dx/dt
Vx = gradient(x,dt);
% Vy = dy/dt
Vy = gradient(y,dt);
% Speed
0.5
speed = sqrt(Vx.^2+Vy.^2);
0
c)
% Computation of the acceleration components
-0.5
% Ax = dVx/dt
Ax = gradient(Vx,dt);
-1
2
% Ay = dVy/dt
Ay = gradient(Vy,dt);
1
0.5
acceleration = sqrt(Ax.^2+Ay.^2);
-1
% Acceleration
-0.5
-2
-1
YOUR TURN
The equations of motion of the particle are given below:
x t cos t
y t 2sin t
z t t
a)
b)
c)
for
0 t 2
Hint: To create several figures, type figure in the command window. A new window will appear.
meshgrid
meshc
contour
shading(interp)
colorbar
a)
Plot the function z for x ranging between 0 and 2, with an increment of 0.1 in both directions using
the meshc command. This command will draw the three-dimensional surface along with a contour
plot underneath.
b)
Make a contour plot of the function above using the contour command. This will only display the
level curves in a horizontal plane. Include labels and a title.
Hint: Using the contour command, you can specify the number of levels you would like to be displayed. The
default number is 10.
SOLUTION
meshc command
close all
clear
6
[x,y]=meshgrid(0:0.1:2*pi);
2
0
-2
z = y.*cos(x).*sin(2*y);
-4
-6
8
meshc(x,y,z)
grid on
4
4
xlabel('x')
2
0
ylabel('y')
zlabel('z')
contour command
title('meshc command')
figure
contour(x,y,z,20)
y
grid on
xlabel('x')
ylabel('y')
2
title('contour command')
3
x
YOUR TURN
The temperature in the interior of a rectangular plate is given by the following function of x
and y:
T x , y
for 0 x, y 2
Plot the temperature as a function of x and y using meshc and contour. Use an increment of
0.05. Display 30 level curves. In both figures add a colorbar, labels, and a title.
fminsearch
a) For functions of a single variable: find the minimum of the function f x 1 xe 2 x , first analytically
and then numerically using the fminsearch command.
Hint : Unlike most MATLAB operations, you dont need to define a vector x before using fminsearch. Simply
type in the function as shown below. fminsearch looks for the local minimum which is closest to the
initial guess you specify as the third parameter.
fminsearch ' f x ', x0
SOLUTION
Analytically: f
x e2 x 2 x 1 0
1
2
0.9
0.8
f(x)
Numerically:
0.7
ans =
0.5
0.5
0.4
5
x
10
b) For functions of several variables: find the minimum of the function f x , y cos xy sin x over the
0 x
domain
using the fminsearch command.
0 y
Hint:
y . Then in
MATLAB, x and y will be represented by the two components: X 1 x and X 2 y , and the
command becomes:
SOLUTION
>> % Plot the surface to visualize the minimum
ans =
1.57082350280598
1.99997995837548
f(x,y)
1
0
3.5
-1
2.5
2
3
1.5
2
1
1
y
0.5
0
YOUR TURN
Consider the following function of two variables:
f x, y x 3 y 1
2
a)
b)
Plot the function on a suitably chosen domain to clearly see the minimum. Add a colorbar, labels, and a
title
c)
polyfit
VL
FD
1
CD V 2 r 2
2
0.05875
0.1003
0.1585
0.4786
3.020
CD
492
256.2
169.8
58.88
10.86
a)
b)
Create two vectors containing the logarithm of the experimental data ln Re and ln CD
Find the line that fits best these points. Display its coefficients on the screen and compare them with the
theoretical result.
c) In the same figure plot the experimental data, the best fit line, and the theoretical line. Add
a legend.
Hint:
The polyfit command finds a polynomial of a specified order that best fits the given data. In this
example, we want to see if the experimental data falls along a straight line. We therefore choose 1 as
the degree of the polynomial.
Hint:
The polyfit command returns a vector containing the coefficients of the polynomial:
n L 1 0 corresponding to P X n X n ... 1 X 1 0
Hint:
To suppress the line connecting the experimental data points, select the big arrow in the figures
menu and double-click on the line. A property editor window will appear. Change the line style to
no line and choose circles for the marker style.
SOLUTION
close all
clear all
% Experimental data
Re = [0.05875 0.1003 0.1585 0.4786 3.020 7.015];
Cd = [492 256.2 169.8 58.88 10.86 5.5623];
% Take the logarithm of these data
lnRe = log(Re);
lnCd = log(Cd);
% Construct the line that fits best data. As we want a
% line, the degree of the polynomial is set to 1.
P = polyfit(lnRe,lnCd,1)
% Define the fitting line, so it can be plotted
lnRefit = linspace(log(0.05875),log(7.015),20);
lnCdfit = P(1)*lnRefit + P(2);
-1.0000
3.17805383
lnRetheo = linspace(log(0.05875),log(7.015),20);
lnCdtheo = log(24) - lnRetheo;
plot(lnRe,lnCd)
hold on
plot(lnRefit,lnCdfit,'--')
plot(lnRetheo,lnCdtheo,'-.')
Experimental data
Best fit
Theoretical line
ln(Cd)
xlabel('ln(Re)')
ylabel('ln(Cd)')
title('drag coefficient on a sphere as a function of the
Reynolds number')
grid on
P=
-0.92980905266427
3.45384753973349
1
-3
-2.5
-2
-1.5
-1
-0.5
ln(Re)
0.5
1.5
Ptheo =
YOUR TURN
The same students have repeated their experiments at Reynolds numbers between 104 and 105
and have found a constant drag coefficient of 0.4775. Assume the density of air is 1.25 kg/m3.
The following table give the drag force on the sphere as a function of the air speed.
V (m/s)
FD (N)
0.036
0.09298
0.10682
0.1568
0.193
Find the radius of the sphere used in the experiments. Follow these steps:
a)
1
CD V 2 r 2
2
1
CD r 2 is now a constant, since the drag coefficient is assumed to be constant. That means
2
that the plot of FD versus V 2 should be close to a straight line. Using polyfit, find an equation of a line
that best fits the data given in the table
1
b) Using the results in part a) extract the value of CD r 2
2
c) Using the numerical values provided, estimate the radius of the sphere
the group
randn
hist
At the assembly line of a big aircraft company, bolts are stored in boxes containing 1000 parts
each. The bolts are supposed to have a nominal diameter of 5 millimetres. But due to the
uncertainty in the manufacturing process, some turn out to be larger and some turn out to be
smaller than nominal.
a) Create a random vector whose components are the diameters of each bolt in a box using the randn
command. The syntax of the randn command is as follows: randn ( M , N ) * A + B, where:
-
M and N determine the size of the output vector, i.e. the number of random values generated. M
corresponds to the number of rows and N to the number of columns. In our example, we want
random diameters for 1000 bolts, so the output will be a vector with M = 1000 and N = 1
A (called standard deviation) is related to the uncertainty in the diameter of the bolts. Here, A =
0.25 mm. This means that about 67% of the bolts have diameters within 0.25 mm of the nominal
diameter.
SOLUTION
Bolts contained in a box
a)
90
80
70
>> hist(x,30)
Number of bolts
60
b)
50
40
30
20
10
0
4.2
4.4
4.6
4.8
5
5.2
Diameter in mm
5.4
5.6
5.8
Hint : The hist command takes the vector generated by the randn command as input and counts the number
of bolts having a diameter within a certain range (a bin). The number of bins is defined by the second
parameter.
YOUR TURN
On the same assembly line, nuts are produced in boxes containing 5000 parts each. All nuts
have a nominal diameter of 5.5 mm, however, the nuts in each box have been machined to
different tolerances. Using subplot, plot the distributions of nuts as a function of their size for
each of the four boxes for which the standard deviations are respectively A=0.45 mm, 0.50 mm,
0.55 mm and 60 mm.
mean
stem
Highway patrol uses a radar to measure the speed of the cars on a freeway. The speed limit is 55
mph. The officers pull over all cars whose speed is greater than 80 mph and write a ticket for
$150 each. If 8000 vehicles are observed on the highway each day, on the average, how much
money does the highway patrol collect each day ? Compute the average over one full year and
assume A = 10 in the randn command.
SOLUTION
stem(S)
xlabel('days')
ylabel('amount')
clear all
close all
% the average of the daily amount is done over a year
for i = 1:365
Savg =
% create a vector whose components are the speed of
% each car taking the freeway
x = randn(8000,1)*10 + 55;
7374.65753424658
12000
% test the speed of each vehicle. If it's greater than 80, add
% 150 to S
8000
amount
for k = 1:length(x)
if x(k) > 80
S(i) = S(i) + 150;
end
6000
4000
end
end
% Compute the average of vector S containing the amount
% collected each day during a year
Savg = mean(S)
2000
50
100
150
200
days
250
300
350
YOUR TURN
Modify the above script compute the average percentage of cars that have a speed of more than
10 mph over the speed limit. Compute your daily average over one year.
trapz
Computes the integral of a function over a given domain using the trapezoidal
method
400
SOLUTION
clear
close
x = linspace(0,1,100)
y = x.^2+x+1;
I = trapz(x,y)
I=
1.8333
Analytical result : I = 11/6 = 1.8333
YOUR TURN
a)
x 0
x2
x 1
dx
b) Compute the same integral numerically using the trapz command. Use an increment of
0.01
c)
Repeat part b), this time with an increment of 0.2. Whats your conclusion?
where:
c
is the speed of light. c = 3.108 m/s
G
is the incident solar power flux G 1350 Watt/m2
A is the area of the spacecraft normal to the sun. The area is assumed to be constant A = 8
m2
The
r
s unit vector directed from the spacecraft toward the sun
orbit
is
planar
and
is
given parametrically
with 0 t 2
by
the
following
equation:
Find the work done by the force of solar radiation on the spacecraft over the following interval
SOLUTION
The work done by a force is computed using the following formula:
is the angle between the velocity vector and the force. Each component of the integral is
computed separately. Then the integral is computed using the trapz command.
clear
% parameters
G = 1350;
A = 8;
c = 3*10^8;
7.1195e+005
YOUR TURN
Suppose that the spacecraft is now travelling in an orbit specified by the following parametric
equation:
where 0 t 2 . Compute the
work done by solar radiation for 0 t
Linear Algebra
24. Basic Matrix Operations
There are many matrix operations in Matlab that make finding solutions to systems equations
much easier than doing so by hand. In order to use these operations, the matrices and vectors
must first be stored in memory. Consider the following matrices and vectors:
3 5 2
A = 0 1 2
3 6 1
2 5 4
B = 4 6 3
4 10 8
1 3
C = 3 2
4 5
Enter the matrices into Matlab and perform the following operations:
(b) AC
(c) CA
(d)
(e)
(a) AB
(e) Reduce A to reduced row echelon form (use the command rref())
(f) Reduce the augmented matrix
via rref()
SOLUTION
We first store the matrices in the command window, and then execute each of the commands. Notice that the
transpose is performed by adding a prime () at the end of the definition.
>> A = [3 5 2; 0 1 2; 3 6 1];
>> B = [2 5 4; 4 6 3; 3 10 8];
>> C = [1 3; 3 2; 4 5];
>> x = [3 2 1];
>> A*B
>> A*C
>> C*A
>> B*x
>> B*x
>> rref(A)
>> Ax = A
>> Ax(:,4) = x %Creates augmented matrix [A|x]
>> rref(Ax)
11 12
25 26
>> C*A
Error using *
Inner matrix dimensions must agree.
>> B*x
ans =
20
27
37
>> B*x'
Error using *
Inner matrix dimensions must agree.
>> rref(A)
ans =
1 0 0
0 1 0
0 0 1
>> rref(Ax)
ans =
1.0000
0
0 1.2222
0 1.0000
0 -0.6667
0 0
1.0000 1.3333
>> A*B
ans =
32 65
10 26
33 61
>> A*C
ans =
26 29
43
19
38
YOUR TURN
Matrices
A , B and C
and vector
2
1 4 5
2 3 6
A = 4 3 2 B = 2 2 1 C = 5
1
-1 2 5
4 5 7
0
1
8
3
7
4
7
2
8
BA
(b)
CA
(c)
AC
(d)
AC T
A\b
1 3 5
A = 2 5 10
3 3 15
for
2 4 5
B = 2 5 10
3 6 9
and a
n 1 vector
(a)
A -1
(b)
B-1
(c) det(A)
for
for
(d) det(B)
SOLUTION
0
>> det(B)
ans =
3
>> A\b
Warning: Matrix is singular to working precision.
ans =
NaN
NaN
-Inf
>> B\b
ans =
12.0000
-8.6667
2.3333
YOUR TURN
Given the following matrices and vectors:
3 2 3
A = 3 1 5
-4 6 1
4 1 -5
B = 4 1 0
-2 3 8
A -1
(b)
B-1
(c) det(A)
for
for
(d) det(B)