Exercise 2
Exercise 2
MATLAB Operator
comment %
Exercises
1. Write a simple script that will calculate the volume of a hollow sphere,
4p 3
ðr ! ri3 Þ
3 o
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.
2. The atomic weight is the weight of a mole of atoms of a chemical element. For
example, the atomic weight of oxygen is 15.9994 and the atomic weight of hydrogen
is 1.0079. Write a script that will calculate the molecular weight of hydrogen
peroxide, which consists of two atoms of hydrogen and two atoms of oxygen. Include
comments in the script. Use help to view the comment in your script.
3. Write an input statement that will prompt the user for the name of a chemical
element as a string. Then, find the length of the string.
4. Write an input statement that will prompt the user for a real number, and store it in a
variable. Then, use the fprintf function to print the value of this variable using two
decimal places.
5. The input function can be used to enter a vector, such as:
>> vec ¼ input('Enter a vector: ')
Enter a vector: 4:7
vec ¼
4 5 6 7
Experiment with this, and determine how the user can enter a matrix.
Exercises 77
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
n without specifying any field width
n in a field width of 10 with four decimal places
n in a field width of 10 with two decimal places
n in a field width of 6 with four decimal places
n in a field width of 2 with four decimal places
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
n without specifying any field width
n in a field width of 5
n in a field width of 8
n in a field width of 3
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 12.340
>> fprintf(
x is 12
>> fprintf(
y is 4.6
>> fprintf(
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 two decimal places. Put comments in the script.
10. Write a script called echoname that will prompt the user for his or her name, and then
echo print the name in a sentence in the following format (use %s to print it):
>> echoname
What is your name? Susan
Wow, your name is Susan!
11. Write a script called echostring that will prompt the user for a string, and will echo
print the string in quotes:
>> echostring
Enter your string: hi there
Your string was: 'hi there'
12. In the metric system, fluid flow is measured in cubic meters per second (m3/s).
A cubic foot per second (ft3/s) is equivalent to 0.028 m3/s. Write a script titled
flowrate that will prompt the user for flow in cubic meters per second and will
78 CHAPTER 2 Introduction to MATLAB Programming
print the equivalent flow rate in cubic feet per second. Here is an example of running
the script. Your script must produce output in exactly the same format as this:
>> flowrate
Enter the flow in m^3/s: 15.2
A flow rate of 15.200 meters per sec
is equivalent to 542.857 feet per sec
13. On average, people in a region spend 8% to 10% of their income on food. Write a script
that will prompt the user for annual income. It will then print the range that would
typically be spent on food annually. Also, print a monthly range.
14. Wing loading, which is airplane weight divided by wing area, is an important design
factor in aeronautical engineering. Write a script that will prompt the user for the
weight of the aircraft in kilograms, and the wing area in meters squared, and then
calculate and print the wing loading of the aircraft in kilograms per square meter.
15. Write a script that assigns values for the x coordinate and then y coordinate of a
point, and then plots this using a green þ.
16. Plot exp(x) for values of x ranging from !2 to 2 in steps of 0.1. Place an appropriate
title on the plot, and label the axes.
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. Next, use the bar
function instead of plot to get a bar chart instead.
18. Create a y vector that stores random integers in the 1 to 100 range. Create an x vector
that iterates from 1 to the length of the y vector. Experiment with the plot function
using different colors, line types, and plot symbols.
19. Plot sin(x) for x values ranging from 0 to p (in separate Figure Windows)
n using 10 points in this range
n using 100 points in this range
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 these data into a matrix, separate it into vectors, and then
plot the data with appropriate axis labels and a title.
21. Create a 3 % 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 % 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 it worked!
Exercises 79
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.
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.
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
>> disp(mwh_to_gj(1.1))
3.9600
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.
28. List some differences between a script and a function.
80 CHAPTER 2 Introduction to MATLAB Programming
29. The velocity of a moving fluid can be found by calculating the difference between the
total and static pressure Pt and Ps. For water, this is given by
pffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi
V ¼ 1:016 Pt ! Ps
Write a function that will receive as input arguments the total and static pressures
and will return the velocity of the water.
30. For a project, some biomedical engineering students are designing a device that will
monitor a person’s heart rate while on a treadmill. The device will let the subject
know when the target heart rate has been reached. A simple calculation of the target
heart rate (THR) for a moderately active person is
35. Write a function that is called pickone, which will receive one input argument x,
which is a vector, and will return one random element from the vector. For example,
>> pickone(4:7)
ans ¼
5
>> disp(pickone(-2:0))
!1
Write a script thirdside that will prompt the user and read in values for b, c, and a
(in degrees), and then calculate and print the value of a with three decimal places.
(Note: To convert an angle from degrees to radians, multiply the angle by p/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 that the script will
call this function.
38. A part is being turned on a lathe. The diameter of the part is supposed to be 20,000 mm.
The diameter is measured every 10 minutes and the results are stored in a file called
partdiam.dat. Create a data file to simulate this. The file will store the time in minutes
and the diameter at each time. Plot the data.
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:
82 CHAPTER 2 Introduction to MATLAB Programming
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.”
40. A file named costssales.dat stores a company’s 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
Write a script called salescosts that will read
1000 the data from this file into a matrix. When
the script is executed, it will do three things.
900 First, it will print how many quarters were
represented in the file, such as:
800 >> salescosts
There were 5 quarters in
700 the file