Reading text values into matlab variables from ASCII files

Boris Gorelik picture Boris Gorelik · Nov 3, 2008 · Viewed 34.6k times · Source

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)

Answer

Adam Holmberg picture Adam Holmberg · Nov 5, 2008

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.