MATLAB: Loading a complicated text file

complicated fileload file

How might I load a text file with data organized like this:
X : 0.0160579
Y : 0.0611
Z : 0.0177048
Y-X-Y : 0.0602318
|
Z
The code I'm trying to use is:
data = dlmread(FileName,':',2,0);
I get an error that says, "Mismatch between file and format character vector.
Trouble reading 'Numeric' field from file (row number 1, field number 1) ==> X 0.0160579\n".
I've tried playing with the delimiter in dlmread and also using other codes like 'load' and 'textscan', with no success (each has their own problem with these files).

Best Answer

dlmread() expects a matrix of numbers, optionally with some header lines. I don't think it expects delimiters of multiple types (spaces, colons, tabs, dashes) on the lines. If you have some really complicated file then you might just have to parse it line by line with fgetl(). It's easy if you just want to take the one number after the colon. Like you could do
% Open the file for reading in text mode.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
lineCounter = 1;
numCounter = 1;
while ischar(textLine)
% Print out what line we're operating on.
fprintf('%s\n', textLine);
% Find the colon
colonLocation = strfind(textLine, ':')
if ~isempty(colonLocation)
numbers(numCounter) = str2double(textLine(colonLocation + 1 : end));
numCounter = numCounter + 1;
end
% Read the next line.
textLine = fgetl(fileID);
lineCounter = lineCounter + 1;
end
% All done reading all lines, so close the file.
fclose(fileID);
numbers is your vector of numbers on the lines.
Related Question