Q:

Create a file which stores on each line a letter, a space, and a real number. For example, it might look like this:

0

e 5.4

f 3.3

c 2.2

Write a script that uses textscan to read from this file. It will print the 

sum of the numbers in the file. The script should error-check the file 

open and close, and print error messages as necessary.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Ch9Ex21.m

% use textscan to read in from a file in the

% format letter number and sum the numbers

fid = fopen('letnum.dat');

if fid == -1

 disp('File open not successful')

else

 %Read in data from file

 C = textscan(fid,'%c %f');

 total = sum(C{2}); %Sum the numbers in the file

 fprintf('The sum of the numbers is %.2f\n',total)

 

 %Error-check file close

 closeresult = fclose(fid);

 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

total answers (1)

Similar questions


need a help?


find thousands of online teachers now