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.

32.9k 14 14 gold badges 75 75 silver badges 109 109 bronze badges asked Nov 24, 2013 at 17:25 157 4 4 silver badges 18 18 bronze badges

3 Answers 3

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, '\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 .