I/O functions:   fopen , fclose , feof , fgetl , fscanf
    (do examples on Matlab!)

  • fid = fopen('fname', 'r')   returns "file handle" fid
      'r' for reading, file must exist
      'w' for writing, file will be overwritten if exists
      'a' for appending, file will be created if it does not exist
      if it fails, fid=-1, can be checked

  • fprintf( fid , '...formatting... \n', variables)   prints on ONE line, \n gives new line
    e.g., if x is a vector:
      fprintf( fid , ' %f ' , x)   will print: values of   x(1) x(2) ... x(N)
      fprintf( fid , ' \n ' )   for new (blank) line

  • fclose(fid)   close the file

  • while( ~feof(fid) )   while NOT at end-of-file

  • Line = fgetl(fid) ;   read one line into string 'Line'

    Reading data from a file of 2 columns:
  • Mat = fscanf( fid, ' %f %f ', [2, M] );   read next M rows of numbers into matrix 'Mat'
        each column of file goes to a row in Mat, then we can extract rows from 'Mat'
        2 = number of columns in file, M = #of rows   (best is to use: [2, inf] to read all remaining rows ).

    Example data file: 'mydata.dat' contains:
       	# mydata.dat:  date, description, ...
    	# x    y
    	  1   31
    	  2   32
    	  3   33
    
    To read it into an array "XY":
    	fid = fopen('mydata.dat', 'r')
    	while( ~feof(fid) )
    		Line = fgetl(fid);	read over 1st line of words
    		Line = fgetl(fid);	read over 2nd line of words
    		  XY = fscanf( fid, ' %f %f', [2, inf] );
    	end %while, file has been read 
    
    Then matrix 'XY' will be:
    	 1  2  3
    	31 32 33 
    and we can extract each row, say for plotting:
    	x = XY(1,:);   y = XY(2,:);
    	plot( x, y )