MATLAB: Does the Import Data wizard not behave as expected when I import files with multiple header rows in MATLAB 7.5 (R2007b)

commaexampleMATLABseparatedvalue

I have a CSV file that looks like the following:
---exampledata.txt---
Channel1,Channel2,Channel3
Units1,Units2,Units3
1,2,3
4,5,6
7,8,9
When I use the Import Data wizard and select the number of text header lines to be 2, the data is imported correctly but the textdata does not make sense:
textdata =
'Channel1,Channel2,Channel3' [] []
'Units1' 'Units2' 'Units3'
In particular, I expect Channel1, Channel2, and Channel3 to be in separate elements of the array.

Best Answer

There is, in general no reason to suppose that headerlines have the same number of delimiters as the data. If the last line has the same number of delimiters, it is treated as column headers. However previous lines usually have very little to do with the data, so they are simply read in as single strings.
To work around this issue, you can use the TEXTSCAN function. The code below illustrates how to do this on the example file given above.
clear all; clc;
fid = fopen('exampledata.txt'); % open file
firstRow = textscan(fid, '%s', 3, 'Delimiter', ','); % read first row of headers
firstRow{1}'
secondRow = textscan(fid, '%s', 3, 'Delimiter', ','); % read second row of headers
secondRow{1}'
temp = textscan(fid, '%n', 3, 'Delimiter', ','); % try to read first line of data
dataRow = 0; % set the number of data lines found so far
while ~isempty(temp{1}) % if the line just read is not empty
dataRow = dataRow + 1; % increment the number of data lines found
data(dataRow,:) = temp{1}'; % copy data from line to data matrix
temp = textscan(fid, '%n', 3, 'Delimiter', ','); % try to read next line of data
end
data
fclose(fid); % close file