How to import data with row and column headers


I want to import data from a text file with row and column headers, and it in a matrix. For instance, the input file looks as follows:

data c1 c2 c3 c4
r1   1  2  3  4
r2   5  6  7  8

Also, is it possible to access the row and column names with the corresponding data element? And is it possible to modify that based on the result of operations?

Thanks in advance.

I would use textscan with an extra %*s in the format string to gobble up the first header column in each row. The first header row should be used to count the number of columns, in case it is unknown:

fid = fopen('input.txt');  %// Open the input file

%// Read the first header row and calculate the number of columns in the file
C = textscan(fid, '%s', 1, 'Delimiter', '\n', 'MultipleDelimsAsOne', true);
cols = numel(regexp(C{1}{1}, '\s*\w+'));

%// Read the rest of the rows and store the data values in a matrix
C = textscan(fid, ['%*s', repmat('%f', 1, cols - 1)]);
A = [C{:}];                %// Store the data in a matrix

fclose(fid);               %// Close the input file

The data is stored in matrix A.