Docsity

File I/O and Plotting in MATLAB, Slides of Computer Programming

Partial preview of the text

Download File I/O and Plotting in MATLAB and more Slides Computer Programming in PDF only on Docsity!

Today

Writing to files

Reading from files

Plot function

Opening a File - fopen

fopen

Opens a file

f = fopen('cs1109.txt','w');

Usage

fid = fopen(filename); fid = fopen(filename, permission);

% returns id's of all open files fids = fopen('all');

Writing to a File

fprintf

Writes formatted data to the file

fprintf(f, '%d %10.5f', n, x);

Usage

count = fprintf(fid, format, A, ..);

Closing a File

fclose

Closes a file

fclose(f);

Usage

status = fclose(fid);

% closes all open files status = fclose('all');

Appending to a File - Example

Sine Table

deg = 91:180; rad = deg (^) * pi/180; s = sin(rad);

% let's open a file f = fopen('sintable.txt','w');

% write values to the file for j = 1:length(deg) fprintf(f,'%2d %8.6f\n',deg(j),s(j)); end

% and close it! fclose(f);

Writing to a File - Batch Version

fprintf is talented

deg = 0:90; rad = deg (^) * pi/180; s = sin(rad);

% let's open a file f = fopen('sintable.txt','w');

% write values to the file data = [deg; s]; fprintf(f,'%2d %8.6f\n',data);

% and close it! fclose(f);

Reading from a File - Example

Sine Table

% let's open a file for reading f = fopen('sintable.txt','r');

% read values from the file [data, count] = fscanf(f,'%d %f', [2 inf]);

% let's display the values disp(data)

% and close it! fclose(f);

Plotting - Ithaca Weather

Read data from file

Ithaca Temperature June 2012

Day Max Min Avg

f = fopen('ithaca june 2012.txt','r'); data = fscanf(f, '%d %d %d %d',[4 inf]); fclose(f);

Plotting - Ithaca Weather

(^600 5 10 15 20 25 )

65

70

75

80

85

90

95

% plot with stars in red color plot(data(1,:),data(2,:),'r*');

Plotting - Ithaca Weather

(^600 5 10 15 20 25 )

65

70

75

80

85

90

95

% connect data points, use circles plot(data(1,:),data(2,:),'roโˆ’');

Plotting - Figure - Example

Example

figure(1) % plot max temp plot(data(1,:),data(2,:),'r')

figure(2) % plot min temp plot(data(1,:),data(3,:),'b')

figure(3) % plot avg temp plot(data(1,:),data(4,:),'g')

Plotting - hold on/off

hold on

holds the current plot

figure hold on plot(data(1,:),data(2,:),'r') plot(data(1,:),data(3,:),'b') plot(data(1,:),data(4,:),'g') hold off % back to normal state

Plotting - Title/Label

(^400 5 10 15 20 25 )

50

60

70

80

90

100 Ithaca Daily Temperature โˆ’ June 2012

Days of June 2012

Temperature (F)

title('Ithaca Daily Temperature โˆ’ June 2012') xlabel('Days of June 2012') ylabel('Temperature (F)')

Plotting - Legend

(^400 5 10 15 20 25 )

50

60

70

80

90

100 Ithaca Daily Temperature โˆ’ June 2012

Days of June 2012

Temperature (F)

Max Min Avg

legend('Max','Min','Avg')