importing numeric data from a text file with column headers, using column headers as vector names

Hi, basically, I need a command/set of commands to do what they illustrate with the wizard here:
I need to do this for a large number of similarly named (numbered) text files, each containing data values for different parameters so I would prefer to be able to make this part of a script rather than doing manually. All files have columns with unique headers ready to be created as vectors, then I will be able to analyse all similar data in bulk.
i.e I have file1.txt, file2.txt and so on.

Answers (2)

If your text file has the consistent format as shown in the link, the importdata() should be enough. Then, maybe you can convert it to a structure that you like.
>> d=importdata('test.txt')
d =
data: [4x4 double]
textdata: {'John' 'Ann' 'Martin' 'Rob'}
colheaders: {'John' 'Ann' 'Martin' 'Rob'}
>> d.data
ans =
88.400000000000006 91.500000000000000 89.200000000000003 77.299999999999997
83.200000000000003 88.000000000000000 67.799999999999997 91.000000000000000
77.799999999999997 76.299999999999997 78.099999999999994 92.500000000000000
92.099999999999994 96.400000000000006 81.200000000000003 84.599999999999994
nevermind, pressed 'generate matlab code' on the wizard. output was this:
function importfile(fileToRead1)
%IMPORTFILE(FILETOREAD1)
% Imports data from the specified file
% FILETOREAD1: file to read
% Auto-generated by MATLAB on 06-Oct-2011 21:31:09
DELIMITER = ';';
HEADERLINES = 1;
% Import the file
newData1 = importdata(fileToRead1, DELIMITER, HEADERLINES);
% Create new variables in the base workspace from those fields.
for i = 1:size(newData1.colheaders, 2)
assignin('base', genvarname(newData1.colheaders{i}), newData1.data(:,i));
end

1 Comment

That's pretty good. Notice that it uses the assignin() function. Many would say you should avoid assignin(), evalin() and eval() as much as possible. You can run y=uiimport('test.txt') (notice that it has a return argument y) and then generate the code. It will create the data in a structure with the header names as the field names. It's much nicer.

Sign in to comment.

Categories

Asked:

on 6 Oct 2011

Community Treasure Hunt

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

Start Hunting!