Darby George 166.2
Helen Dee 143.5
Giovanni Lupa 192.4
Cat Donovan 215.1
Create this data file first. Then, write a script readpatwts that will first
attempt to open the file. If the file open is not successful, an error
message should be printed. If it is successful, the script will read the
data into strings, one line at a time. Print for each person the name in
the form ‘last,first’ followed by the weight. Also, calculate and print
the average weight. Finally, print whether or not the file close was
successful. For example, the result of running the script would look like
this:
>> readpatwts
George,Darby 166.2
Dee,Helen 143.5
Lupa,Giovanni 192.4
Donovan,Cat 215.1
The ave weight is 179.30
File close successful
Ch9Ex14.m
% Reads names and weights of patients for an experiment
% Prints in form last, first and then weight
% Calculates and prints average patient weight
fid = fopen('patwts.dat');
if fid == -1
disp('File open not successful')
else
i = 0;
% Store all weights in a vector
weight = [];
while feof(fid) == 0
% Get first name, last name, and weight
aline = fgetl(fid);
[fname, rest] = strtok(aline);
[lname, strwt] = strtok(rest);
weight = [weight; str2num(strwt)];
fprintf('%s,%s %s\n',lname,fname,strwt)
end
closeresult = fclose(fid);
fprintf('The ave weight is %.2f\n',mean(weight))
if closeresult == 0
disp('File close successful')
else
disp('File close not successful')
end
end
need an explanation for this answer? contact us directly to get an explanation for this answer