Monday, September 1, 2008

[Matlab] Reading Ascii data with matlab

function DataFromFile=ReadAsciiData(FileName,FMT,NumFmt)
% Function to read ascii data from a file with given format
% Usage:
%            DataFromFile=GetAsciiData(FileName,FMT,NumFmt)
%       e.g.,
%            Data=GetAsciiData('data.dat','%8f',4)
%            The data will be read in following command:
%                   Data=fscanf(fid,'%8f %8f %8f %8f',[4 inf]);
%            Same as: Data=ReadAsciiData('data.dat','%8f %8f %8f %8f')
%            http://scriptdemo.blogspot.com

fid=fopen(FileName,'r');
if (fid==-1)
   error(['Error in reading ',FileName,', Please check the file name.']);
else
   if ~exist('FMT');
      FMT='%f';
      if ~exist('NumFmt') NumFmt=1; end
      for N=1:NumFmt-1
           FMT=[FMT,' ','%f'];
      end
   else
      if ~exist('NumFmt')
         NumFmt=length(find(FMT=='%'));
      else
         for N=1:NumFmt-1
               FMT=[FMT,' ',FMT];
         end
      end
   end
   DataFromFile=fscanf(fid,FMT,[NumFmt,inf]); % [DataFromFile]=fscanf(fid,FMT);
   DataFromFile=DataFromFile';
   fclose(fid);
end

No comments:

ShowCalendar