How do I make the names in my file header the names of the variables I load?

13 views (last 30 days)
I have column headers at the top of my file and I want to name my variables in MATLAB the same names.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 1 Jul 2015
Assume that a file named 'myData.txt' stores tab delimited data whose column wise contents you would like to assign to the variables with the names same as the column headers in the file. This is the contents of 'myData.txt':
Student Major Grade Graduation
John Engineering 89 2003
Marcy Computer Science 83 2005
Don Biology 82 2004
Diane Applied Math 88 2004
'myData.txt' is attached for reference.
Step 1: Read the column headers and data from the file.
%open file
fid = fopen('myData.txt','r');
%Read the first line of the file containing the header information
headerline = fgetl(fid);
%The file pointer is now at the beginning of the second line. Use TEXTSCAN to read the columns of data.
data = textscan(fid,'%s%s%d%d','Delimiter','\t')
%close file
fclose(fid);
Step 2:
Convert the column headers into individual elements stored in a cell array.
headers = textscan(headerline,'%s','Delimiter','\t');
Step 3: Use EVAL statements to copy the column data into the individual
for k = 1:length(headers{:})
eval([headers{1}{k} '= data{k};']);
end
For R2013b onwards, you can also use "readTable" to import a .txt file and create variables having names similar to column headers. Assume a .txt file stores comma delimited data whose column wise contents you would like to assign to the variables with the names same as the column headers in the file.  This is the contents of the file 'myTableData.txt':
Student,Major,Grade,Graduation
John,Engineering,89,2003
Marcy,Computer Science,83,2005
Don,Biology,82,2004
Diane,Applied Math,88,2004
'myTableData.txt' is attached for reference.
Step 1:
Read the file into MATLAB using "readTable"
data=readtable('myTableData.txt');
Step 2:
Use EVAL to create variable names similar to the column headers of the .txt file
for i=1:width(data)
x = data.Properties.VariableNames(i);
eval(sprintf('%s = data.%s', x{1}, x{1}));
end
  2 Comments
Guillaume
Guillaume on 15 Apr 2015
Al, that answer is outdated anyway. In modern versions of matlab (since 2013b)
data = readtable('mydata.txt')
is all that is needed
Guillaume
Guillaume on 16 Apr 2015
Please start a question of your own. It will have more visibility and thus more people will contribute.
With your question attach a typical file you're trying to import (or a simplified version).

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!