I am trying to write a robust read command for my application. I want the read code to be able to handle whether the *.txt has a header (title) line or not.
The user will create a trajectory file that is always 7 columns wide and an unknown length. The first line can either be a title line for the columns or not. Typically I create my files in excel and then save them using the "Unicode Text" format. I know I could use xlsread() but I would prefer to read from a text file for versatility. Here's my current code:
In_fID=fopen([Dir,File],'r');
FirstLine=fgetl(In_fID);
model_data=textscan(In_fID,'%f %f %f %f %f %f %f');
if ischar(FirstLine)
model_data=cell2mat(model_data);
else
FirstLine=cell2mat(FirstLine);
model_data=cel2mat(model_data);
model_data=[FirstLine;model_data];
end
Regardless of whether the first line is a header line like "Time x y z r p yw" or the first coordinate of my trajectory (For example: "0 0 0 0 0 0 0") ischar(Firstline)
always returns true (1). Does anyone know how I can fix this?
ischar
is not the best choice for the check you are trying to do.
You can do a check on the first value:
In_fID = fopen( [Dir,File] , 'r' ) ;
FirstValue = fscanf(In_fID,'%f',1) ; %// this will return empty if the first text does not represent a number
if isempty( FirstValue )
Headers = textscan( In_fID , '%s %s %s %s %s %s %s' , 1 ) ; %// read the header titles
else
fseek( In_fID , 0 , 'bof' ) ; %// Rewind the cursor to the beginning of the file
end
model_data=textscan(In_fID,'%f %f %f %f %f %f %f'); %// read your data normally
fclose(In_fID) ; %// don't forget to close your file ;)
This tries to read a numeric value from the file.
If it fails (e.g. if the first text in file cannot be converted to a number), it reads a line of text header title (and move the cursor to the next line).
If the first reading return an actual value, the program rewind (replace the cursor at the beginning of the file).
The last line reads the rest of the file as numeric values.