views:

8830

answers:

3

Consider the following file

var1 var2 variable3
1     2    3
11    22   33

I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:

variable_names = char('var1', 'var2', 'variable3');

I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option.

Note that there can be an arbitrary number of variables (columns)

A: 

Just use textscan with different format specifiers.

fid = fopen(filename,'r');
heading = textscan(fid,'%s %s %s',1);
fgetl(fid); %advance the file pointer one line
data = textscan(fid,'%n %n %n');%read the rest of the data
fclose(fid);

In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.

Revah
There can be an arbitrary number of variables (columns)
bgbg
If you don't know the number of columns in advance then you will have to read the file one line at a time. If you call textscan with a single %s and no limiting number, it will read N number of strings from the line. I think this is better/faster than using strtok.
Revah
+2  A: 

Hi,

If the header is on the first row then

A = dlmread(filename,delimString,2,1);

will read the numeric data into the Matrix A.

You can then use

fid = fopen(filename)
headerString = fscanf(fid,'%s/n') % reads header data into a string
fclose(fid)

You can then use strtok to split the headerString into a cell array. Is one approach I can think of deal with an unknown number of columns

Edit

fixed fscanf function call

Azim
+4  A: 

I suggest importdata for operations like this:

d = importdata('filename.txt');

The return is a struct with the numerical fields in a member called 'data', and the column headers in a field called 'colheaders'.

Another useful interface for importing manipulating data like these is the 'dataset' class available in the Statistics Toolbox.

Adam