Chapter 2: Introduction To MATLAB Programming Exercises
Chapter 2: Introduction To MATLAB Programming Exercises
Exercises
1) Write a simple script that will calculate the volume of a hollow sphere,
4 3 3
(ro ri )
3
where ri is the inner radius and ro is the outer radius. Assign a value to a variable for
the inner radius, and also assign a value to another variable for the outer radius.
Then, using these variables, assign the volume to a third variable. Include
comments in the script.
Ch2Ex1.m
% This script calculates the volume of a hollow sphere
mat =
4 5 6
9 10 11
mat =
0 0
0 0
6) Experiment, in the Command Window, with using the fprintf function for real
numbers. Make a note of what happens for each. Use fprintf to print the real
number 12345.6789.
realnum = 12345.6789;
without specifying any field width
>> fprintf('The number is %f\n', realnum)
The number is 12345.678900
in a field width of 10 with 4 decimal places
>> fprintf('The number is %10.4f\n', realnum)
The number is 12345.6789
in a field width of 10 with 2 decimal places
>> fprintf('The number is %10.2f\n', realnum)
The number is 12345.68
in a field width of 6 with 4 decimal places
>> fprintf('The number is %6.4f\n', realnum)
The number is 12345.6789
in a field width of 2 with 4 decimal places
>> fprintf('The number is %2.4f\n', realnum)
The number is 12345.6789
7) Experiment, in the Command Window, with using the fprintf function for
integers. Make a note of what happens for each. Use fprintf to print the integer
12345.
intnum = 12345;
without specifying any field width
>> fprintf('The number is %d\n', intnum)
The number is 12345
in a field width of 5
>> fprintf('The number is %5d\n', intnum)
The number is 12345
in a field width of 8
>> fprintf('The number is %8d\n', intnum)
The number is 12345
in a field width of 3
>> fprintf('The number is %3d\n', intnum)
The number is 12345
8) Create the following variables
x = 12.34;
y = 4.56;
Then, fill in the fprintf statements using these variables that will accomplish the
following:
>> fprintf('x is %8.3f\n', x)
x is 12.340
>> fprintf('x is %.f\n', x)
x is 12
>> fprintf('y is %.1f\n', y)
y is 4.6
>> fprintf('y is %-8.1f!\n', y)
y is 4.6 !
9) Write a script to prompt the user for the length and width of a rectangle, and
print its area with 2 decimal places. Put comments in the script.
Ch2Ex9.m
% Calculate the area of a rectangle
% Prompt the user for the weight and wing area of the plane
plane_weight = input('Enter the weight of the airplane: ');
wing_area = input('Enter the wing area: ');
plot(x,y, 'g+')
16) Plot exp(x) for values of x ranging from ‐2 to 2 in steps of 0.1. Put an
appropriate title on the plot, and label the axes.
Ch2Ex16.m
% Plots exp(x)
x = -2:0.1:2;
y = exp(x);
plot(x,y,'*')
title('Exp(x)')
xlabel('x')
ylabel('exp(x)')
17) Create a vector x with values ranging from 1 to 100 in steps of 5. Create a vector
y which is the square root of each value in x. Plot these points. Now, use the bar
function instead of plot to get a bar chart instead.
Ch2Ex17.m
% Plots same x and y points using bar and plot
clf
x = 1:5:100;
y = sqrt(x);
plot(x,y,'*')
title('sqrt(x)')
figure(2)
bar(x,y)
title('sqrt(x)')
18) Create a y vector which stores random integers in the 1 to 100 range. Create an
x vector which iterates from 1 to the length of the y vector. Experiment with the
plot function using different colors, line types, and plot symbols.
Ch2Ex18.m
% Experiment with plot symbols and line types
y = randi([1, 100],1,15)
x = 1:length(y);
clf
plot(x,y,'rv')
figure(2)
plot(x,y,'g*:')
19) Plot sin(x) for x values ranging from 0 to (in separate Figure Windows):
using 10 points in this range
using 100 points in this range
Ch2Ex19.m
% Plots sin(x) with 10 points and 100 points in range 0 to pi
x = linspace(0,pi,10);
y = sin(x);
clf
figure(1)
plot(x,y,'k*')
title('sin(x) with 10 points')
figure(2)
x = linspace(0,pi);
y = sin(x);
plot(x,y,'k*')
title('sin(x) with 100 points')
20) Atmospheric properties such as temperature, air density, and air pressure are
important in aviation. Create a file that stores temperatures in degrees Kelvin at
various altitudes. The altitudes are in the first column and the temperatures in the
second. For example, it may look like this:
1000 288
2000 281
3000 269
5000 256
10000 223
Write a script that will load this data into a matrix, separate it into vectors, and then
plot the data with appropriate axis labels and a title.
Ch2Ex20.m
% Read altitudes and temperatures from a file and plot
load alttemps.dat
altitudes = alttemps(:,1);
temps = alttemps(:,2);
plot(altitudes,temps,'k*')
xlabel('Altitudes')
ylabel('Temperatures')
title('Atmospheric Data')
21) Create a 3 x 6 matrix of random integers, each in the range from 50 to 100.
Write this to a file called randfile.dat. Then, create a new matrix of random integers,
but this time make it a 2 x 6 matrix of random integers, each in the range from 50 to
100. Append this matrix to the original file. Then, read the file in (which will be to a
variable called randfile) just to make sure that worked!
>> mat = randi([50,100], 3,6)
mat =
91 96 64 99 98 57
96 82 77 58 74 71
56 54 98 99 90 96
>> save randfile.dat mat -ascii
>> newmat = randi([50,100], 2,6)
newmat =
90 83 93 84 87 83
98 51 97 88 70 58
>> save randfile.dat newmat -ascii -append
>> load randfile.dat
>> randfile
randfile =
91 96 64 99 98 57
96 82 77 58 74 71
56 54 98 99 90 96
90 83 93 84 87 83
98 51 97 88 70 58
22) Create a file called “testtan.dat” comprised of two lines with three real numbers
on each line (some negative, some positive, in the ‐1 to 3 range). The file can be
created from the Editor, or saved from a matrix. Then, load the file into a matrix
and calculate the tangent of every element in the resulting matrix.
>> mat = rand(2,3)*4-1
mat =
1.8242 0.1077 -0.6115
-0.8727 -0.8153 2.2938
>> save testtan.dat mat -ascii
>> load testtan.dat
>> tan(testtan)
ans =
-3.8617 0.1081 -0.7011
-1.1918 -1.0617 -1.1332
23) Write a function calcrectarea that will calculate and return the area of a
rectangle. Pass the length and width to the function as input arguments.
calcrectarea.m
function area = calcrectarea(length, width)
% This function calculates the area of a rectangle
% Format of call: calcrectarea(length, width)
% Returns the area
24) Write a function called fn that will calculate y as a function of x, as follows:
y = x3 – 4x2 + sin(x)
Here are two examples of using the function:
>> help fn
Calculates y as a function of x
>> y = fn(7)
y =
147.6570
fn.m
function out = fn(x)
% Calculates y as a function of x
Renewable energy sources such as biomass are gaining increasing attention. Biomass
energy units include megawatt hours (MWh) and gigajoules (GJ). One MWh is
equivalent to 3.6 GJ. For example, one cubic meter of wood chips produces 1 MWh.
25) Write a function mwh_to_gj that will convert from MWh to GJ. Here are some
examples of using the function.
>> mwh = 3.3;
>> gj = mwh_to_gj(mwh)
gj =
11.8800
>> disp(mwh_to_gj(1.1))
3.9600
mwh_to_gj.m
function out = mwh_to_gj(mwh)
% Converts from MWh to GJ
26) The velocity of an aircraft is typically given in either miles/hour or
meters/second. Write a function that will receive one input argument, the velocity
of an airplane in miles per hour and will return the velocity in meters per second.
The relevant conversion factors are: one hour = 3600 seconds, one mile = 5280 feet,
and one foot = .3048 meters.
convertVel.m
function velmps = convertVel(velmph)
% Convert the velocity of an aircraft from
% miles per hour to meters per second
% Format of call: convertVel(mph)
% Returns velocity in mps
velmps = velmph/3600*5280*.3048;
end
27) If a certain amount of money (called the principal P) is invested in a bank
account, earning an interest rate i compounded annually, the total amount of money
Tn that will be in the account after n years is given by:
n
Tn = P (1 + i)
Write a function that will receive input arguments for P, i, and n, and will return the
total amount of money Tn. Also, give an example of calling the function.
function totMoney = account(p,i,n)
% Calculates the amount of money in an account
% after n years at interest rate i with a
% principal p invested
% Format of call: account(p,i,n)
% Returns total of money after n years
totMoney = p * (1+i)^n;
end
>> format bank
>> total = account(50000,0.05,10)
total =
81444.73
28) List some differences between a script and a function.
A function has a header whereas a script does not.
A function typically has end at the end of the file.
A function is called whereas a script is executed.
Arguments are passed to functions but not to scripts.
Functions can return arguments whereas scripts cannot.
The block comment is typically in the beginning of a script but under the
function header.
29) The velocity of a moving fluid can be found from the difference between the
total and static pressures Pt and Ps. For water, this is given by
P Ps
V = 1.016 t
Write a function that will receive as input arguments the total and static pressures
and will return the velocity of the water.
fluidvel.m
function waterVel = fluidvel(totp, statp)
% Calculates the velocity of water given the
% total and static pressures
% Format: fluidvel(total pressure, static pressure)
% Returns the velocity of the water
rainToSnow.m
function outsnow = rainToSnow(rain)
% Calculate equivalent amount of snow
% given rainfall in inches
% Format of call: rainToSnow(rain)
% Returns equivalent snowfall
tetVol.m
function vol = tetVol(len)
% Calculates the volume of a regular tetrahedron
% Format of call: tetVol(side length)
% Returns volume
>> disp(pickone(-2:0))
-1
len = length(invec);
ran = randi([1, len]);
elem = invec(ran);
end
36) A function can return a vector as a result. Write a function vecout that will
receive one integer argument and will return a vector that increments from the
value of the input argument to its value plus 5, using the colon operator. For
example,
>> vecout(4)
ans =
4 5 6 7 8 9
vecout.m
function outvec = vecout(innum)
% Create a vector from innum to innum + 5
% Format of call: vecout(input number)
% Returns a vector input num : input num+5
outvec = innum:innum+5;
end
37) If the lengths of two sides of a triangle and the angle between them are known,
the length of the third side can be calculated. Given the lengths of two sides (b and
c) of a triangle, and the angle between them α in degrees, the third side a is
calculated as follows:
a2 = b2 + c2 – 2 b c cos(α)
Write a script thirdside that will prompt the user and read in values for b, c, and α
(in degrees), and then calculate and print the value of a with 3 decimal places.
(Note: To convert an angle from degrees to radians, multiply the angle by /180).
The format of the output from the script should look exactly like this:
>> thirdside
Enter the first side: 2.2
Enter the second side: 4.4
Enter the angle between them: 50
For more practice, write a function to calculate the third side, so the script will call
this function.
thirdside.m
% Calculates the third side of a triangle, given
% the lengths of two sides and the angle between them
load partdiam.dat
mins = partdiam(:,1);
diams = partdiam(:,2);
plot(mins,diams,'k*')
xlabel('minutes')
ylabel('part diameter')
39) A file “floatnums.dat” has been created for use in an experiment. However, it
contains float (real) numbers and what is desired instead is integers. Also, the file is
not exactly in the correct format; the values are stored columnwise rather than
rowwise. For example, if the file contains the following:
90.5792 27.8498 97.0593
12.6987 54.6882 95.7167
91.3376 95.7507 48.5376
63.2359 96.4889 80.0280
9.7540 15.7613 14.1886
what is really desired is:
91 13 91 63 10
28 55 96 96 16
97 96 49 80 14
Create the data file in the specified format. Write a script that would read from the
file floatnums.dat into a matrix, round the numbers, and write the matrix in the
desired format to a new file called intnums.dat.
Ch2Ex39.m
% Reads in float numbers stored column-wise from a file,
% rounds them to integers and writes row-wise to a new file
load floatnums.dat
inums = round(floatnums)';
save intnums.dat inums -ascii
40) A file called costssales.dat stores for a company some cost and sales figures for
the last n quarters (n is not defined ahead of time). The costs are in the first column,
and the sales are in the second column. For example, if five quarters were
represented, there would be five lines in the file, and it might look like this:
1100 800
1233 650
1111 1001
1222 1300
999 1221
Write a script called salescosts that will read the data from this file into a matrix.
When the script is executed, it will do three things. First, it will print how many
quarters were represented in the file, such as:
>> salescosts
There were 5 quarters in the file
Next, it will plot the costs using black circles and sales using black stars (*) in a
Figure Window with a legend (using default axes) as seen in Figure 2.8.
Company Costs and Sales
1300
Costs
Sales
1200
1100
1000
900
800
700
600
1 1.5 2 2.5 3 3.5 4 4.5 5
Quarter
Figure 2.8 Plot of Cost and Sales data
Finally, the script will write the data to a new file called newfile.dat in a different
order. The sales will be the first row, and the costs will be the second row. For
example, if the file is as shown above, the resulting file will store the following:
800 650 1001 1300 1221
1100 1233 1111 1222 999
It should not be assumed that the number of lines in the file is known.
salescosts.m
load costssales.dat
costs = costssales(:,1);
sales = costssales(:,2);
len = length(costs); % or sales