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.
fid = fopen('myData.txt','r');
headerline = fgetl(fid);
data = textscan(fid,'%s%s%d%d','Delimiter','\t')
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
Best Answer