Chapter 6: MATLAB Programs Exercises
Chapter 6: MATLAB Programs Exercises
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
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
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
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]);
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
degRad.m
function rad = degRad(deg)
% Converts an angle from degrees to radians
% Format of call degRad(degrees)
% Returns the angle in radians
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
rad = degRadii(deg);
fprintf('The angle %.1f degrees is \n', deg)
fprintf('equivalent to %.1f radians\n', rad)
end
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
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
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 = 1:maxl;
meters = ft * .3048;
chart = [ft;meters]';
[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
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
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
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
outarea = sqrt(s*(s-a)*(s-b)*(s-c));
end
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
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]';
print_press.m
function print_press(bar, atm, psi)
% Prints pressure grades in bars and in
% equivalent atm and psi
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
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
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
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
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:
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