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

조회 수: 8 (최근 30일)
I have column headers at the top of my file and I want to name my variables in MATLAB the same names.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2015년 7월 1일
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
Guillaume
Guillaume 2015년 4월 15일
Al, that answer is outdated anyway. In modern versions of matlab (since 2013b)
data = readtable('mydata.txt')
is all that is needed
Guillaume
Guillaume 2015년 4월 16일
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).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by