Consider the following two vectors of temperatures in Celsius degrees to Fahrenheit, using a for-loop and then prints them on screen.
Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]
Fdegrees = [-20, -15, -5, 0, 10, 15, 30, 35, 40]
(A) Write a function that takes an input vector of temperatures, and a string which is either 'F2C'
or C2F
. Then, converts the input temperature vector from Fahrenheit to Celsius if the input string is 'F2C'
, otherwise converts the input temperature vector from Celsius to Fahrenheit if the input string is 'C2F'
, otherwise outputs an error message and aborts the program.
(A) Write this function using while-loop construct (you can name the function convertTempFor.m
).
(B) Write this function using for-loop construct (you can name the function convertTempWhile.m
).
(C) Write this function using vectorization concept (you can name the function convertTempVec.m
).
(D) Use MATLAB built-in timing functions to measure the performance of the three functions in the above.
Here are some example calls to these functions,
InVec = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40];
convertTempFor(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
convertTempWhile(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
convertTempVec(InVec,'C2F')
ans = -4 5 14 23 32 41 50 59 68 77 86 95 104
Consider the following example code, which converts a list of temperature values from Celsius to Fahrenheit, using a for-loop and then prints them on screen.
Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]
print (' C F')
for C in Cdegrees:
F = (9.0/5)*C + 32
print ('%5d %5.1f' % (C, F))
C F
-20 -4.0
-15 5.0
-10 14.0
-5 23.0
0 32.0
5 41.0
10 50.0
15 59.0
20 68.0
25 77.0
30 86.0
35 95.0
40 104.0
Write a while-loop implementation of the above code.