0% found this document useful (0 votes)
81 views7 pages

Exercise 2

This document provides exercises to practice basic MATLAB programming concepts including: 1. Writing scripts to calculate volume, molecular weight, and other formulas. 2. Using input, output, and plot functions. 3. Creating and manipulating vectors and matrices. 4. Writing functions to perform calculations. The exercises cover a wide range of foundational MATLAB skills like variable assignment, conditional logic, loops, plotting, file I/O, and writing reusable functions.

Uploaded by

Mahmoud Shendy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views7 pages

Exercise 2

This document provides exercises to practice basic MATLAB programming concepts including: 1. Writing scripts to calculate volume, molecular weight, and other formulas. 2. Using input, output, and plot functions. 3. Creating and manipulating vectors and matrices. 4. Writing functions to perform calculations. The exercises cover a wide range of foundational MATLAB skills like variable assignment, conditional logic, loops, plotting, file I/O, and writing reusable functions.

Uploaded by

Mahmoud Shendy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

76 CHAPTER 2 Introduction to MATLAB Programming

MATLAB Reserved Words


function end

MATLAB Functions and Commands


type ylabel legend
input title grid
disp axis bar
fprintf clf load
plot figure save
xlabel hold

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)

147.6570

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:
>> gj ¼ mwh_to_gj(mwh)
gj ¼
11.8800

>> disp(mwh_to_gj(1.1))
3.9600

>> help mwh_to_gj


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 ¼
0.3048 meters.
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:
Tn ¼ P ð1 þ iÞn

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

THR ¼ ð220 ! AÞ & :6


where A is the person’s age. Write a function that will calculate and return the THR.
31. An approximation for a factorial can be found using Stirling’s formula:
pffiffiffiffiffiffiffiffi"n#n
n! ' 2pn
e
Write a function to implement this, passing the value of n as an argument.
32. The cost of manufacturing n units (where n is an integer) of a particular product at a
factory is given by the equation
CðnÞ ¼ 5n2 ! 44n þ 11
Write a script mfgcost that will
n prompt the user for the number of units n
n call a function costn that will calculate and return the cost of manufacturing n units
n print the result (the format must be exactly as shown next)
Next, write the function costn, which simply receives the value of n as an input
argument, and calculates and returns the cost of manufacturing n units.
Here is an example of executing the script:
>> mfgcost
Enter the number of units: 100
The cost for 100 units will be $45611.00
>>
33. The desired conversion depends on temperature and other factors, but an
approximation is that 1 inch of rain is equivalent to 6.5 inches of snow. Write a script
that prompts the user for the number of inches of rain, calls a function to return the
equivalent amount of snow, and prints this result. Write the function as well!
1
pffiffiffi 3
34. The volume V of a regular tetrahedron is given by V ¼ 12 2s , where s is the length of
the sides of the equilateral triangles that form the faces of the tetrahedron. Write a
program to calculate such a volume. The program will consist of one script and one
function. The function will receive one input argument, which is the length of the
sides, and will return the volume of the tetrahedron. The script will prompt the user
for the length of the sides, call the function to calculate the volume, and print the
result in a nice sentence format. For simplicity, we will ignore units.
Exercises 81

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

>> help pickone


pickone(x) returns a random element from vector x
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
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 a in degrees, the third side a is calculated as
follows:
a2 ¼ b2 þ c2 ! 2 b c cosðaÞ

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

The third side is 3.429

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

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.”
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:

Company Costs and Sales 1100 800


1300 1233 650
Costs 1111 1001
Sales 1222 1300
1200
999 1221

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

Next, it will plot the costs using black circles


600 and sales using black stars (*) in a
1 1.5 2 2.5 3 3.5 4 4.5 5
Quarter Figure Window with a legend (using default
axes) as seen in Figure 2.8.
FIGURE 2.8 Plot of cost and sales data
Finally, the script will write the data to
Note a new file called newfile.dat in a different
It should not be order. The sales will be in the first row, and the costs in the second row. For example,
assumed that the if the file is as shown before, the resulting file will store the following:
number of lines in
800 650 1001 1300 1221
the file is known.
1100 1233 1111 1222 999

You might also like