Chapter 6: MATLAB Programs
Exercises
1) Write a function that will receive as an input argument a temperature in degrees
Fahrenheit, and will return the temperature in both degrees Celsius and Kelvin. The
conversion factors are: C = (F – 32) * 5/9 and K = C + 273.15.
conv_f_to_kc.m
function [ctemp ktemp] = conv_f_to_kc(ftemp)
% Converts a temperature in degrees F to
% both degrees C and K
% Format of call: conv_f_to_kc(Fahrenheit temp)
% Returns degrees C then degrees K
ctemp = (ftemp - 32) * 5/9;
ktemp = ctemp + 273.15;
end
2) Write a function that will receive as an input argument a number of kilometers
(K). The function will convert the kilometers to miles and to U.S. nautical miles, and
return both results. The conversions are: 1K = 0.621 miles and 1 US nautical mile =
1.852 K.
kToMilesNaut.m
function [miles nautmiles] = kToMilesNaut(kms)
% Converts a distance in kilometers to miles and U.S. nautical miles
% Format kToMilesNaut(kilometers)
% Returns miles and then nautical miles
miles = kms .* 0.621;
nautmiles = kms ./ 1.852;
end
3) A vector can be represented by its rectangular coordinates x and y or by its polar
coordinates r and θ. For positive values of x and y, the conversions from rectangular
to polar coordinates in the range from 0 to 2 are r = x 2 y 2 and θ =
arctan(y/x). The function for arctan is atan. Write a function recpol to receive as
input arguments the rectangular coordinates and return the corresponding polar
coordinates.
recpol.m
function [r theta] = recpol(x,y)
% Converts vector coordinates from
% rectangular coordinates x and y to polar
% Format of call: recpol(x,y)
% Returns polar coordinates r then theta
r = sqrt(x^2 + y^2);
theta = atan(y/x);
end
4) A vector can be represented by its rectangular coordinates x and y or by its polar
coordinates r and θ. For positive values of x and y, the conversions from rectangular
to polar coordinates in the range from 0 to 2 are r = x 2 y 2 and θ =
arctan(y/x). Write a function to receive as input arguments the rectangular
coordinates and return the corresponding polar coordinates.
Just kidding!
Instead, convert from polar to rectangular; the conversions from polar to
rectangular are x = r cos(θ) and y = r sin(θ).
polar_to_rect.m
function [x y] = polar_to_rect(r, theta)
% Converts from polar to rectangular coordinates
% Format of call: polar_to_rect(r, theta)
% Returns x then y
x = r*cos(theta);
y = r*sin(theta);
end
5) Write a function to calculate the volume and surface area of a hollow cylinder. It
receives as input arguments the radius of the cylinder base and the height of the
cylinder. The volume is given by r2 h, and the surface area is 2 r h.
vol_surfarea.m
function [vol surfarea] = vol_surfarea(rad, ht)
% Calculates the volume and surface area of a
% hollow cylinder, given the radius and height
% Format of call: vol_surfarea(radius, height)
% Returns volume then surface area
vol = pi * rad^2 * ht;
surfarea = 2 * pi * rad * ht;
end
6) Write a function that will receive the radius of a circle and will print both the
radius and diameter of the circle in a sentence format. This function will not return
any value; it simply prints.
printCircleInfo.m
function printCircleInfo(rad)
% Prints the radius and diameter of a circle
% Format: printCircleInfo(radius)
% Does not return any values
fprintf('A circle with a radius of %.2f\n', rad)
fprintf(' has a diameter of %.2f\n', rad*2)
end
7) Write a function that will receive as an input argument a length in inches, and will
print in a sentence format the length in both inches and centimeters (1 inch = 2.54
cm). Note that this function will not return any value.
printLengths.m
function printLengths(inch)
% Receives a length in inches and prints
% the length in inches and centimeters
% Format of call: printLengths(lenght in inches)
% Does not return any values
fprintf('A length of %.1f inches is\n', inch)
fprintf(' equivalent to %.1f cm.\n', inch*2.54)
end
8) Write a function that will receive an integer n and a character as input arguments,
and will print the character n times.
printNChars.m
function printNChars(n, ch)
% Receives n and a character and prints
% the character n times
% Format of call: printNChars(n, character)
% Does not return any values
for i = 1:n
fprintf('%c', ch)
end
fprintf('\n')
end
9) Convert the printstars script from Chapter 4 to a function that receives as inputs
the number of rows and columns, and prints a box of asterisks with the specified
number of rows and columns.
printStarsFn.m
function printStarsFn(rows, columns)
% Prints a box of stars
% size to print specified by 2 input arguments
% Format of cal: printStarsFn(# rows, # columns)
% Does not return any values
% loop over the rows
for i=1:rows
% for every row loop to print *'s and then one \n
for j=1:columns
fprintf('*')
end
fprintf('\n')
end
end
10) Convert the multtable function from Chapter 4 to a function that receives as
input arguments the number of rows and columns and prints a multiplication table
(rather than returning the matrix).
prtMulttable.m
function prtMulttable(rows, columns)
% Prints a multiplication table with rows
% from 1 to r and columns from 1 to c
% Format of call: prtMulttable(r,c)
% Does not return any values
for i = 1:rows
for j = 1:columns
fprintf('%4d', i * j);
end
fprintf('\n')
end
end
11) Write a function that will receive a matrix as an input argument, and prints it in
a table format.
printMat.m
function printMat(mat)
% Prints a matrix in a table format
% Assumes a fairly small matrix of ints
% Format of call: printMat(matrix)
% Does not return any values
[r c] = size(mat);
for i = 1:r
for j = 1:c
fprintf('%6d', mat(i,j))
end
fprintf('\n')
end
end
12) Write a function that receives a matrix as an input argument, and prints a
random row from the matrix.
printRanRow.m
function printRanRow(mat)
% Prints a random row from a matrix
% Assumes a fairly small matrix of ints
% Format of call: printRanRow(matrix)
% Does not return any values
[r c] = size(mat);
ranrow = randi([1,r]);
fprintf('%d ', mat(ranrow,:))
fprintf('\n')
end
13) Write a function that receives a count as an input argument, and prints the value
of the count in a sentence that would read “It happened 1 time.” if the value of the
count is 1, or “It happened xx times.” if the value of count (xx) is greater than 1.
printCount.m
function printCount(count)
% Prints a count in a correct sentence
% with an 's' for plural or not
% Format of call: printCount(count)
% Does not return any value
fprintf('It happened %d time', count)
if count > 1
fprintf('s')
end
fprintf('.\n')
end
14) Write a function that will print an explanation of temperature conversions. The
function does not receive any input arguments; it simply prints.
printTempConvInfo.m
function printTempConvInfo
% Prints some info on temperature conversions
% Format of call: printTempConvInfo
% or printTempConvInfo()
% Does not return any values
fprintf('There are different temperature scales.\n')
fprintf('Given a temperature in one system, it is\n')
fprintf(' easy to convert to another.\n')
fprintf('For example, given a temperature in Fahrenheit,\n ')
fprintf('the conversion to Celsius is C = (F - 32)*5/9\n')
fprintf(' and to Kelvin is K = C + 273.15\n')
end
15) Write a function that receives an x vector, a minimum value, and a maximum
value, and plots sin(x) from the specified minimum to the specified maximum.
plotXMinMax.m
function plotXMinMax(x, xmin, xmax)
% Plots sin(x) from the minimum value of x
% specified to the maximum
% Format of call: plotXMinMax(x, x minimum, x maximum)
% Does not return any values
x = linspace(xmin,xmax);
plot(x,sin(x),'*')
xlabel('x')
ylabel('sin(x)')
end
16) Write a function that prompts the user for a value of an integer n, and returns
the value of n. No input arguments are passed to this function.
promptForN.m
function outn = promptForN
% This function prompts the user for n
% It error-checks to make sure n is an integer
% Format of call: promptForN or promptForN()
% Returns an integer entered by the user
inputnum = input('Enter an integer for n: ');
num2 = int32(inputnum);
while num2 ~= inputnum
inputnum = input('Invalid! Enter an integer: ');
num2 = int32(inputnum);
end
outn = inputnum;
end
17) Write a function that prompts the user for a value of an integer n, and returns a
vector of values from 1 to n. The function should error‐check to make sure that the
user enters an integer. No input arguments are passed to this function.
promptNVec.m
function outvec = promptNVec
% This function prompts the user for n
% It error-checks to make sure n is a positive integer
% It returns a vector from 1 to n
% Format of call: promptNVec or promptNVec()
% Returns a vector 1:n
inputnum = input('Enter a positive integer for n: ');
num2 = int32(inputnum);
while num2 ~= inputnum || num2 < 0
inputnum = input('Invalid! Enter a positive integer: ');
num2 = int32(inputnum);
end
outvec = 1:inputnum;
end
18) Write a script that will:
Call a function to prompt the user for an angle in degrees
Call a function to calculate and return the angle in radians . (Note: radians =
180)
Call a function to print the result
Write all of the functions, also. Note that the solution to this problem involves four
M‐files: one which acts as a main program (the script), and three for the functions.
Ch6Ex18.m
% Script calls functions to:
% prompt for an angle in degrees
% convert to radians
% print both
deg = promptAng;
rad = degRad(deg);
prtDegRad(deg,rad)
promptAng.m
function deg = promptAng
% Prompts for an angle in degrees
% Format of call: promptAng or promptAng()
% Returns an angle in degrees
deg = input('Enter an angle in degrees: ');
end
degRad.m
function rad = degRad(deg)
% Converts an angle from degrees to radians
% Format of call degRad(degrees)
% Returns the angle in radians
rad = deg * pi / 180;
end
prtDegRad.m
function prtDegRad(deg, rad)
% Prints an angle in degrees and radians
% Format of call: prtDegRad(degrees, radians)
% Does not return any values
fprintf('The angle %.1f degrees is \n', deg)
fprintf('equivalent to %.1f radians\n', rad)
end
19) Modify the above program in Exercise 18 so that the function to calculate the
angle is a subfunction to the function that prints.
Ch6Ex19.m
% Script calls functions to:
% prompt for an angle in degrees
% print degrees and radians, calling a
% subfunction to convert to radians
deg = promptAng;
prtDegRadii(deg)
promptAng.m
function deg = promptAng
% Prompts for an angle in degrees
% Format of call: promptAng or promptAng()
% Returns an angle in degrees
deg = input('Enter an angle in degrees: ');
end
prtDegRadii.m
function prtDegRadii(deg)
% Prints an angle in degrees and radians
% Calls a subfunction to convert to radians
% Format of call: prtDegRadii(degrees)
% Does not return any values
rad = degRadii(deg);
fprintf('The angle %.1f degrees is \n', deg)
fprintf('equivalent to %.1f radians\n', rad)
end
function rad = degRadii(deg)
% Converts an angle from degrees to radians
% Format of call degRadii(degrees)
% Returns the angle in radians
rad = deg * pi / 180;
end
20) Write a program to calculate and print the area and circumference of a circle.
There should be one script and three functions to accomplish this (one that prompts
for the radius, one that calculates the area and circumference, and one that prints).
Ch6Ex20.m
% This script calls functions to:
% prompt the user for the radius of a circle
% calculate and return the area & circumference
% print the results
% Ignore units and error-checking for simplicity
radius = readRadius;
[area circ] = areaCirc(radius);
printAreaCirc(radius, area, circ)
readRadius.m
function radius = readRadius
% This function prompts the user and reads the radius
% Format of call: readRadius or readRadius()
% Does not return any values
disp('When prompted, please enter the radius in inches.')
radius = input('Enter the radius: ');
end
areaCirc.m
function [area, circum] = areaCirc(rad)
% This function calculates the area and
% the circumference of a circle
% Format of call: areaCirc(radius)
% Returns the area then circumference
area = pi * rad .* rad;
circum = 2 * pi * rad;
end
printAreaCirc.m
function printAreaCirc(rad,area,circ)
% Prints the radius, area, and circumference
% of a circle
% Format of call: printAreaCirc(radius,area,circumference)
% Does not return any values
fprintf('For a circle with a radius of %.1f,\n', rad)
fprintf(' the area is %.1f and the circumference is %.1f\n',...
area, circ)
end
21) The lump sum S to be paid when interest on a loan is compounded annually is
given by S = P(1 + i)n where P is the principal invested, i is the interest rate, and n is
the number of years. Write a program that will plot the amount S as it increases
through the years from 1 to n. The main script will call a function to prompt the
user for the number of years (and error‐check to make sure that the user enters a
positive integer). The script will then call a function that will plot S for years 1
through n. It will use .05 for the interest rate and $10,000 for P.
Ch6Ex21.m
% Plots the amount of money in an account
% after n years at interest rate i with a
% principal p invested
% Call a function to prompt for n
n = promptYear;
% Call a function to plot
plotS(n, .05, 10000)
promptYear.m
function outn = promptYear
% This function prompts the user for # of years n
% It error-checks to make sure n is a positive integer
% Format of call: promptYear or promptYear()
% Returns the integer # of years
inputnum = input('Enter a positive integer for n: ');
num2 = int32(inputnum);
while num2 ~= inputnum || num2 < 0
inputnum = input('Invalid! Enter a positive integer: ');
num2 = int32(inputnum);
end
outn = inputnum;
end
plotS.m
function plotS(n, i, p)
% Plots the lump sum S for years 1:n
% Format of call: plotS(n,i,p)
% Does not return any values
vec = 1:n;
s = p * (1+i).^ vec;
plot(vec,s,'k*')
xlabel('n (years)')
ylabel('S')
end
22) The following script prtftlens loops to:
call a function to prompt the user for a length in feet
call a function to convert the length to inches
call a function to print both
prtftlens.m
for i = 1:3
lenf = lenprompt();
leni = convertFtToIn(lenf);
printLens(lenf, leni)
end
Write all of the functions.
lenprompt.m
function ft = lenprompt
% Prompts the user for a length in feet
% Format of call: lenprompt or lenprompt()
% Returns the lenght in feet
ft = input('Enter a length in feet: ');
while ft <= 0
ft = input('Error! Enter a length in feet: ');
end
end
convertFtToIn.m
function inches = convertFtToIn(feet)
% Convert a length in feet to inches
% Format of call: convertFtToIN(feet)
% Returns a length in inches
inches = feet .* 12;
end
printLens.m
function printLens(feet, inches)
% Prints a length in feet and inches
% Format of call: printLens(feet, inches)
% Does not return any values
fprintf('A length of %.1f feet is equivalent', feet)
fprintf(' to %.1f inches\n', inches)
end
23) Write a program to write a length conversion chart to a file. It will print lengths
in feet, from 1 to an integer specified by the user, in one column and the
corresponding length in meters ( 1 foot = 0.3048 m) in a second column. The main
script will call one function that prompts the user for the maximum length in feet;
this function must error‐check to make sure that the user enters a valid positive
integer. The script then calls a function to write the lengths to a file.
Ch6Ex23.m
% Write a length conversion chart to a file
% Call a function to get the max length in feet
maxl = promptMaxL;
% Call a function to write the chart to a file
lengthChart(maxl)
promptMaxL.m
function maxl = promptMaxL
% This function prompts the user for a max length in feet
% It error-checks to make sure it is a positive integer
% Format of call: promptmaxl or promptmaxl()
% Returns the integer maximum length in feet
inputnum = input('Enter the maximum length: ');
num2 = int32(inputnum);
while num2 ~= inputnum | num2 < 0
inputnum = input('Invalid! Enter a positive integer: ');
num2 = int32(inputnum);
end
maxl = inputnum;
end
lengthChart.m
function lengthChart(maxl)
% Creates a chart of converting feet to
% meters and writes it to a file
% Format of call: lengthChart(maximum length)
% Does not return any values
ft = 1:maxl;
meters = ft * .3048;
chart = [ft;meters]';
save ftmetchart.dat chart -ascii
end
24) For a prism that has as its base an n‐sided polygon and height h, the volume V
and surface area A are given by:
n n 2
V = hS 2 cot A = S cot nSh
4 n 2 n
where S is the length of the sides of the polygons. Write a script that calls a function
getprism that prompts the user for the number of sides n, the height h, and the
length of the sides S and returns these three values. It then calls a function calc_v_a
that calculates and returns the volume and surface area, and then finally a function
printv_a that prints the results. The built‐in function in MATLAB for cotangent is
cot.
Ch6Ex24.m
% Calulates the volume and surface area of a prism
% with an n-sided polygon as base and height h
% Call a function to get inputs, a function to
% calculate volume and surface area, and another
% function to print the results
[n, h, s] = getprism;
[v, sa] = calc_v_a(n,h,s);
printv_a(n,h,s,v,sa)
getprism.m
function [n,h,s] = getprism
% Prompts the user for the number of sides n,
% the height h and the length of sides s for a
% prism with an n-sided base
% Format of call: getprism or getprism()
% Returns n, h, and s in that order
% Even better: error-check all of these
n = input('Enter the number of sides: ');
h = input('Enter the height: ');
s = input('Enter the length of the sides: ');
end
calc_v_a.m
function [v sa] = calc_v_a(n,h,s)
% Calculates the volume and surface area for a prism
% Format: calc_v_a(# sides, height, side length)
% Returns the volume and then surface area
v = n/4*h*s^2*cot(pi/n);
sa = n/2*s^2*cot(pi/n) + n*s*h;
end
printv_a.m
function printv_a(n,h,s,v,sa)
% Prints the volume and surface area for
% a prism with an n-sided base with length
% of sides s and height h
% Format of call: printv_a(n,h,s,v,sa)
% Does not return any values
fprintf('\nFor a prism with a height %.1f\n',h)
fprintf('and a %d-sided base with side\n', n)
fprintf('lengths %.1f, the volume is %.1f\n',s,v)
fprintf('and the surface area is %.1f\n',sa)
end
E
25) The resistance R in ohms of a conductor is given by R = where E is the
I
potential in volts and I is the current in amperes. Write a script that will:
Call a function to prompt the user for the potential and the current
Call a function that will print the resistance; this will call a subfunction to
calculate and return the resistance
Write the functions as well.
Ch6Ex25.m
% Read in the potential and current and print the resistance
% Call a function to prompt for the potential and current
[e i] = promptEI;
% Call a function to print the resistance
printResis(e,i)
promptEI.m
function [e, i] = promptEI
% Prompts the user for potential e
% and current i
% Format of call: promptEI or promptEI()
% Returns the potential E and then current I
% ignores error-checking for simplicity
e = input('Enter the potential e: ');
i = input('Enter the current I: ');
end
printResis.m
function printResis(e,i)
% This function prints the resistance
% Format of call: printResis(potential, current)
% Does not return any values
% Call a subfunction to calculate the resistance
r = calcResis(e,i);
fprintf('For a conductor with a potential %.2f\n', e)
fprintf(' and a current %.2f\n', i)
fprintf(' the resistance is %.2f\n', r)
end
function r = calcResis(e,i)
% This function calculates the resistance
% Format of call: calcResis(potential, current)
% Returns the resistance
r = e/i;
end
26) The power in watts is given by P = EI. Modify the program in Exercise 25 to
calculate and print both the resistance and the power. Modify the subfunction so
that it calculates and returns both values.
Ch6Ex26.m
% Read in the potential and current and print
% both the resistance and the power
% Call a function to prompt for the potential and current
[e i] = promptEI;
% Call a function to print the resistance and power
printResisPow(e,i)
promptEI.m
function [e, i] = promptEI
% Prompts the user for potential e
% and current i
% Format of call: promptEI or promptEI()
% Returns the potential E and then current I
% ignores error-checking for simplicity
e = input('Enter the potential e: ');
i = input('Enter the current I: ');
end
printResisPow.m
function printResisPow(e,i)
% This function prints the resistance and power
% Format of call: printResis(potential, current)
% Does not return any values
% Call a subfunction to calculate resistance & power
[r p] = calcResisPow(e,i);
fprintf('For a conductor with a potential %.2f', e)
fprintf(' and a current %.2f\n', i)
fprintf(' the resistance is %.2f', r)
fprintf(' and the power is %.2f\n',p)
end
function [r p] = calcResisPow(e,i)
% This function calculates the resistance
% Format of call: calcResis(potential, current)
% Returns the resistance
r = e/i;
p = e*i;
end
27) The distance between any two points (x1,y1) and (x2,y2) is given by:
distance = ( x1 x 2 ) 2 ( y1 y 2 ) 2
The area of a triangle is:
area = s * ( s a ) * ( s b) * ( s c)
where a, b, and c are the lengths of the sides of the triangle, and s is equal to half the
sum of the lengths of the three sides of the triangle. Write a script that will prompt
the user to enter the coordinates of three points that determine a triangle (e.g. the x
and y coordinates of each point). The script will then calculate and print the area of
the triangle. It will call one function to calculate the area of the triangle. This
function will call a subfunction that calculates the length of the side formed by any
two points (the distance between them).
Ch6Ex27.m
% Calculate the area of a triangle given the
% coordinates of the 3 points that determine it
% Prompt the user for the coordinates of the points
x1 = input('Enter the x coordinate of point 1: ');
y1 = input('Enter the y coordinate of point 1: ');
x2 = input('Enter the x coordinate of point 2: ');
y2 = input('Enter the y coordinate of point 2: ');
x3 = input('Enter the x coordinate of point 3: ');
y3 = input('Enter the y coordinate of point 3: ');
% Call a function to calculate the area, then print it
area = triarea(x1,y1,x2,y2,x3,y3);
fprintf('The area of the triangle is %.2f\n', area)
triarea.m
function outarea = triarea(x1,y1,x2,y2,x3,y3)
% Calculates the area of the triangle
% Format of call: triarea(x1,y1,x2,y2,x3,y3)
% Returns the area of the triangle
a = dist(x1,y1,x2,y2);
b = dist(x2,y2,x3,y3);
c = dist(x3,y3,x1,y1);
s = 0.5*(a+b+c);
outarea = sqrt(s*(s-a)*(s-b)*(s-c));
end
function outd = dist(x1,y1,x2,y2)
% Calculates the distance between any two points
% Format of call: dist(x1,y1,x2,y2)
% Returns the distance between the two points
outd = sqrt((x1-x2)^2 + (y1-y2)^2);
end
Satellite navigation systems have become ubiquitous. Navigation systems based in
space such as the Global Positioning System (GPS) can send data to handheld personal
devices. The coordinate systems that are used to represent locations present this data
in several formats.
28) The geographic coordinate system is used to represent any location on Earth as
a combination of altitude and longitude values. These values are angles that can be
written in the decimal degrees (DD) form or the degrees, minutes, seconds (DMS)
form just like time. For example, 24.5° is equivalent to 24°30’0”. Write a script that
will prompt the user for an angle in DD form and will print in sentence format the
same angle in DMS form. The script should error‐check for invalid user input. The
angle conversion is to be done by calling a separate function in the script. Here is an
example of running the script:
>> DMSscript
Enter an angle in decimal degrees form: 24.5588
24.56 degrees is equivalent to 24 degrees, 33 minutes,
31.68 seconds
DMSscript.m
% Prompts the user for an angle in decimal degrees (DD) form,
% calls a function to converto to degrees, minutes, seconds (DMS)
% and prints the result
angles = input('Enter an angle in decimal degrees form: ');
while angles <= 0
angles = input('Invalid! Enter an angle in decimal degrees form: ');
end
[d m s] = DMS(angles);
fprintf('%.2f degrees is equivalent to %d deg, %d minutes,\n', ...
angles, d, m)
fprintf('%.2f seconds\n', s)
DMS.m
function [degree minutes seconds] = DMS(angles)
% converts angle in DD form to DMS form
% Format of call: DMS(DD angle)
% Returns degrees, minutes, seconds
degree = floor(angles);
minutes = floor((angles - degree)*60);
seconds = ((angles - degree)*60 - minutes)*60;
end
29) Write a program to write a temperature conversion chart to a file. The main
script will:
call a function that explains what the program will do
call a function to prompt the user for the minimum and maximum
temperatures in degrees Fahrenheit, and return both values. This function
checks to make sure that the minimum is less than the maximum, and calls a
subfunction to swap the values if not.
call a function to write temperatures to a file: the temperature in degrees F
from the minimum to the maximum in one column, and the corresponding
temperature in degrees Celsius in another column. The conversion is C = (F –
32) * 5/9.
Ch6Ex29.m
% Writes a temperature conversion chart to a file
% Explain the program
explainTemp
% Prompt the user for min and max F temps
[tmin, tmax] = tempMinMax;
% Write the F temps and corresponding C temps to file
fandCTemps(tmin, tmax)
explainTemp.m
function explainTemp
% Explains that the program will write a temperature
% conversion chart from F to C to a file
fprintf('This program writes a temperature conversion')
fprintf(' chart to a file fcchart.dat.\n')
fprintf('\nIt prompts the user for a minimum and maximum')
fprintf(' temp in degrees F\n')
fprintf('It writes the F temps from min to max in one')
fprintf(' column\n and correspoding C temps in another\n')
end
tempMinMax.m
function [tmin, tmax] = tempMinMax
% Prompts the user for min and max F temps
% and makes sure min < max
% Format of call: tempMinMax or tempMinMax()
% Returns min and max temperatures in F
tmin = input('Enter the minimum F temp: ');
tmax = input('Enter the maximum F temp: ');
if tmin > tmax
[tmin tmax] = swap(tmin, tmax);
end
end
function [outa outb] = swap(ina, inb)
% swaps the values of arguments
% Format of call: swap(a,b)
% Returns b then a
outa = inb;
outb = ina;
end
fandCTemps.m
function fandCTemps(tmin, tmax)
% Writes the F and C temps to a file
% Format of call: fandCTemps(min temp, max temp)
% Does not return any values
f = tmin:tmax;
c = (f-32)*5/9;
mat = [f;c]';
save fcchart.dat mat -ascii
end
30) A bar is a unit of pressure. Polyethylene water pipes are manufactured in
pressure grades, which indicate the amount of pressure in bars that the pipe can
support for water at a standard temperature. The following script printpressures
prints some common pressure grades, as well as the equivalent pressure in atm
(atmospheres) and psi (pounds per square inch). The conversions are:
1 bar = 0.9869atm = 14.504 psi
The script calls a function to convert from bars to atm and psi, and calls another
function to print the results. You may assume that the bar values are integers.
printpressures.m
% prints common water pipe pressure grades
commonbar = [4 6 10];
for bar = commonbar
[atm, psi] = convertbar(bar);
print_press(bar,atm,psi)
end
convertbar.m
function [atm, psi] = convertbar(bar)
% Converts common pressure grades for polyethylene water pipes
% from bars to atm and psi
% Format of call: convertbar(bar)
% Returns pressure in atm and then psi
atm = bar .* 0.9869;
psi = bar .* 14.504;
end
print_press.m
function print_press(bar, atm, psi)
% Prints pressure grades in bars and in
% equivalent atm and psi
fprintf('For a pressure of %d bars,', bar)
fprintf(' the equivalent is %.1f psi\n', psi)
fprintf('and %.1f atm\n\n', atm)
end
31) The following script (called circscript) loops n times to prompt the user for the
circumference of a circle (where n is a random integer). Error‐checking is ignored
to focus on functions in this program. For each, it calls one function to calculate the
radius and area of that circle, and then calls another function to print these values.
The formulas are r = c/(2Π) and a = Π r2 where r is the radius, c is the
circumference, and a is the area. Write the two functions.
circscript.m
n = round(rand*4)+1;
for i = 1:n
circ = input('Enter the circumference of the circle: ');
[rad area] = radarea(circ);
dispra(rad,area)
end
radarea.m
function [radius area] = radarea(circ)
% Calculates the radius and area of a circle,
% given the circumference
% Format of call: radarea(circumference)
% Returns the radius then area
radius = circ/(2*pi);
area = pi * radius ^2;
end
dispra.m
function dispra(radius, area)
% Prints the radius and area of a circle
% Format of call: dispra(radius, area)
% Does not return any values
fprintf('The radius of the circle is %.2f\n', radius)
fprintf('The area of the circle is %.2f\n', area)
end
32) Write a script that will ask the user to choose his or her favorite science class,
and print a message regarding that course. It will call a function to display a menu
of choices (using the menu function); this function will error‐check to make sure
that the user pushes one of the buttons. The function will return the number
corresponding to the user’s choice. The script will then print a message.
Ch6Ex32.m
% Displays a menu and asks the user for his/her
% favorite science class, and prints a message
% based on that choice
% Call a function to display the menu
choice = scioption;
switch choice
case 1
disp('Biology, huh?')
case 2
disp('Chemistry rocks')
case 3
disp('Physics indeed')
end
scioption.m
function choice = scioption
% Print the menu of science course options and
% error-check until the user pushes one of the buttons
% Format of call: scioption or scioption()
% Returns the integer of the user's choice, from 1-3
choice = menu('Choose a science class', 'Biology', ...
'Chemistry', 'Physics');
% If the user closes the menu box rather than
% pushing one of the buttons, choice will be 0
while choice == 0
disp('Error - please choose one of the options.')
choice = menu('Choose a science class', 'Biology', ...
'Chemistry', 'Physics');
end
end
33) Write a menu‐driven program to convert a time in seconds to other units
(minutes, hours, and so on). The main script will loop to continue until the user
chooses to exit. Each time in the loop, the script will generate a random time in
seconds, call a function to present a menu of options, and print the converted time.
The conversions must be made by individual functions (e.g. one to convert from
seconds to minutes). All user‐entries must be error‐checked.
Ch6Ex33.m
% Menu-driven program to convert a time from seconds
% to other units specified by the user
% Generate a random time in seconds
rantime = randi([1 10000]);
% Call a function to display a menu and get a choice
choice = timeoption;
% Choice 3 is to exit the program
while choice ~= 3
switch choice
case 1
fprintf('%d seconds is %.1f minutes\n',...
rantime, secsToMins(rantime));
case 2
fprintf('%d seconds is %.2f hours\n',...
rantime, secsToHours(rantime));
end
% Generate a random time in seconds
rantime = randi([1 10000]);
% Display menu again and get user's choice
choice = timeoption;
end
timeoption.m
function choice = timeoption
% Print the menu of options and error-check
% until the user pushes one of the buttons
% Format of call: timeoption or timeoption()
% Returns the integer value of the choice, 1-3
choice = menu('Choose a unit', 'Minutes', ...
'Hours', 'Exit');
% If the user closes the menu box rather than
% pushing one of the buttons, choice will be 0
while choice == 0
disp('Error - please choose one of the options.')
choice = menu('Choose a unit', 'Minutes', ...
'Hours', 'Exit');
end
end
secsToMins.m
function mins = secsToMins(seconds)
% Converts a time from seconds to minutes
% Format secsToMins(seconds)
% Returns the time in minutes
mins = seconds / 60;
end
secsToHours.m
function hours = secsToHours(seconds)
% Converts a time from seconds to hours
% Format secsToHours(seconds)
% Returns the time in hours
hours = seconds / 3600;
end
34) Write a menu‐driven program to investigate the constant . Model it after the
program that explores the constant e. Pi () is the ratio of a circle’s circumference to
its diameter. Many mathematicians have found ways to approximate . For
example, Machin’s formula is:
1 1
= 4 arctan ‐ arctan
4 5 239
Leibniz found that can be approximated by:
4 4 4 4 4 4
= ‐ + ‐ + ‐ + …
1 3 5 7 9 11
This is called a sum of a series. There are six terms shown in this series. The first
term is 4, the second term is –4/3, the third term is 4/5, and so forth. For example,
the menu‐driven program might have the following options:
Print the result from Machin’s formula.
Print the approximation using Leibniz’ formula, allowing the user to specify how
many terms to use.
Print the approximation using Leibniz’ formula, looping until a “good”
approximation is found.
Exit the program.
Ch6Ex34.m
% This script explores pi
% Call a function to display a menu and get a choice
choice = pioption;
% Choice 4 is to exit the program
while choice ~= 4
switch choice
case 1
% Print result from Machin's formula
pimachin
case 2
% Approximate pi using Leibniz,
% allowing user to specify # of terms
pileibnizn
case 3
% Approximate pi using Leibniz,
% until a "good" approximation is found
pileibnizgood
end
% Display menu again and get user's choice
choice = pioption;
end
pioption.m
function choice = pioption
% Print the menu of options and error-check
% until the user pushes one of the buttons
% Format of call: pioption or pioption()
% Returns integer of user's choice, 1-4
choice = menu('Choose a pi option', 'Machin', ...
'Leibniz w/ n', 'Leibniz good', 'Exit Program');
% If the user closes the menu box rather than
% pushing one of the buttons, choice will be 0
while choice == 0
disp('Error - please choose one of the options.')
choice = menu('Choose a pi option', 'Machin', ...
'Leibniz w/ n', 'Leibniz good', 'Exit Program');
end
end
pimachin.m
function pimachin
% Approximates pi using Machin's formula and prints it
% Format of call: pimachin or pimachin()
% Does not return any values
machinform = 4 * atan(1/5) - atan(1/239);
fprintf('Using the MATLAB constant, pi = %.6f\n', pi)
fprintf('Using Machin''s formula, pi = %.6f\n',4*machinform)
end
function pileibnizn
% Approximates and prints pi using Leibniz' formula
% Prompt user for number of terms n
% Format of call: pileibnizn or pileibnizn()
% Does not return any values
fprintf('Approximate pi using Leibiz'' formula\n')
% Call a subfunction to prompt user for n
n = askforn;
approxpi = 0;
denom = -1;
termsign = -1;
for i = 1:n
denom = denom + 2;
termsign = -termsign;
approxpi = approxpi + termsign * (4/denom);
end
fprintf('An approximation of pi with n = %d is %.2f\n', ...
n, approxpi)
end
function outn = askforn
% This function prompts the user for n
% It error-checks to make sure n is a positive integer
% Format of call: askforn or askforn()
% Returns positive integer n
inputnum = input('Enter a positive integer for n: ');
num2 = int32(inputnum);
while num2 ~= inputnum | num2 < 0
inputnum = input('Invalid! Enter a positive integer: ');
num2 = int32(inputnum);
end
outn = inputnum;
end
35) Modify the function func2 from Section 6.4.1 that has a persistent variable
count. Instead of having the function print the value of count, the value should be
returned.
func2ii.m
function outc = func2ii
% Returns the value of a persistent variable
% that counts the # of times the function is called
% Format of call: func2ii or func2ii()
% Returns the value of the persistent count
persistent count
if isempty(count)
count = 0;
end
count = count + 1;
outc = count;
end
36) Write a function per2 that receives one number as an input argument. The
function has a persistent variable that sums the values passed to it. Here are the
first two times the function is called:
>> per2(4)
ans =
4
>> per2(6)
ans =
10
per2.m
function outstat = per2(num)
% Persistent variable sums the numbers
% passed to this function
% Format of call: per2(input number)
% Returns the persistent sum of input arguments
persistent mysum
if isempty(mysum)
mysum = 0;
end
mysum = mysum + num;
outstat = mysum;
end
37) What would be the output from the following program? Think about it, write
down your answer, and then type it in to verify.
testscope.m
answer = 5;
fprintf('Answer is %d\n',answer)
pracfn
pracfn
fprintf('Answer is %d\n',answer)
printstuff
fprintf('Answer is %d\n',answer)
pracfn.m
function pracfn
persistent count
if isempty(count)
count = 0;
end
count = count + 1;
fprintf('This function has been called %d times.\n',count)
end
printstuff.m
function printstuff
answer = 33;
fprintf('Answer is %d\n',answer)
pracfn
fprintf('Answer is %d\n',answer)
end
>> testscope
Answer is 5
This function has been called 1 times.
This function has been called 2 times.
Answer is 5
Answer is 33
This function has been called 3 times.
Answer is 33
Answer is 5
>>
38) Assume a matrix variable mat, as in the following example:
mat =
4 2 4 3 2
1 3 1 0 5
2 4 4 0 2
The following for loop
[r c] = size(mat);
for i = 1:r
sumprint(mat(i,:))
end
prints this result:
The sum is now 15
The sum is now 25
The sum is now 37
Write the function sumprint.
sumprint.m
function sumprint(vec)
% Prints the result of a persistent sum
% of the values in vectors that are passed
% Format of call: sumprint(vector)
% Returns the persistent sum of all input vectors
persistent mysum
if isempty(mysum)
mysum = 0;
end
mysum = mysum + sum(vec);
fprintf('The sum is now %d\n', mysum)
end