How do I make the names in my file header the names of the variables I load?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 26 de Abr. de 2010
Comentada: Guillaume
el 16 de Abr. de 2015
I have column headers at the top of my file and I want to name my variables in MATLAB the same names.
Respuesta aceptada
MathWorks Support Team
el 1 de Jul. de 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 comentarios
Guillaume
el 15 de Abr. de 2015
Al, that answer is outdated anyway. In modern versions of matlab (since 2013b)
data = readtable('mydata.txt')
is all that is needed
Guillaume
el 16 de Abr. de 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).
Más respuestas (0)
Ver también
Categorías
Más información sobre Workspace Variables and MAT-Files en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!