In: Computer Science
Please answer this using MATLAB (Not c or c++) and make sure to provide proper commenting:
a. Write a function that writes a series of random Fahrenheit
temperatures and their corresponding Celsius temperatures to a
tab-delimited le. Use 32 to 212 as your temperature range.
From the user, obtain the following:
1) The number of temperatures to randomly generate.
2) The name of the output file.
b. Write a function that reads a file produced by part (a).
Focusing only on the Celsius temperatures in the le, calculate and
display to screen the following:
1) Mean or Average
2) Minimum
3) Maximum
MATLAB Code:
(a)
File: randomTemperature.m
function randomTemperature()
% Function that generates random Fahrenheit
temperatures and converts and writes Celsius values to file
fileName = input(" Please enter the name of your
file: ");
iterCnt = input(" Please enter the number of
iterations: ");
% Opening file for writing
fileID = fopen(fileName,'w');
% Min and Max range
minRange = 32;
maxRange = 212;
% Printing header
fprintf(fileID, " Fahrenheit Celsius");
% Iterating over given number of
iterations
for i = 1:iterCnt
% Generating Fahrenheit
temperature
fhTemp =
minRange+rand(1)*(maxRange-minRange);
% Converting into
Celsius using conversion formula
celTemp = ( (5/9.0) * ( fhTemp -
32.0 ) );
% Writing to file
fprintf(fileID, "\n %.2f
\t %.2f ", fhTemp, celTemp);
endfor
% Closing file
fclose(fileID);
endfunction
Sample Run:
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
(b)
File: temperatureStatistics.m
function temperatureStatistics()
% Function that reads Celsius temperatures and
prints Average, max and min values
% Opening file for reading
fid = fopen("temperatures.txt", "r");
% Reading header
header = fgets(fid);
% Reading values
values = fscanf(fid, "%f");
% Closing file
fclose(fid);
% Extracting Celsius values
celsiusTemperatures = values(2:2:end);
% Printing Statistics
printf("\n Average Celsius Temperature: %.2f
\n", mean(celsiusTemperatures) );
printf("\n Minimum Celsius Temperature: %.2f
\n", min(celsiusTemperatures) );
printf("\n Maximum Celsius Temperature: %.2f
\n", max(celsiusTemperatures) );
endfunction
Sample Run: