MATLAB: Importing a text file with two headers and data so that the headers are the variable names

importing .txttext headers as variable names

I have a large amount of data and usually just manually import it in by deleting the units row (2nd row) and using the first row as the variable name. But I would like to make a script to make my life easier, but have wasted too much time already trying to figure it out.
Basically, is there an easy script to import a .txt file, delete the second row and use the first row as the variable names of the numerical data arrays?

Best Answer

There are a lot of ways to deal with reading in data. This is one imaginative way of doing it, but I think it should work. (Here I assume each value is separated by a single space, and each value is read in as a double). Maybe someone has a simpler idea.
fid = fopen('myfile.txt','r');
firstline = fgetl(fid);
numvars = numel(strread(firstline,'%s'));
fgetl(fid); %<-- Skip the second line
data = textscan(fid,repmat('%f',1,numvars));
eval(['[' strrep(firstline,' ',',') '] = deal(data{:})'])
fclose(fid);