Reading files with headers into matlab

Here's a handy code sniplet that enables you to read a file with columns of data with headers into MATLAB:

  1. function importfile(filename)
  2.  
  3. % import the file
  4. newdata = importdata(filename);
  5.  
  6. % create new variables in the base workspace from these fields
  7. vars = fieldnames(newdata);
  8. for i=1:length(vars),
  9. assignin('base', vars{i}, newdata.(vars{i}));
  10. end

This will give you three variables in your workspace:

  • colheaders: a list of all the variable names, extracted from the header
  • data: a matrix with all your data in it
  • textdata: essentially the same thing as colheaders

Leave a Reply

You must be logged in to post a comment.