Importing text files into variables with the same name
Show older comments
Hi all,
I am trying to load a series of txt files into matlab from a single directory. They all have two columns of numbers with the head "s" and "ACD 0", which looks somewhat like this:
"s" "ADC 0"
0.00000000 -0.031433
0.00020000 -0.025940
0.00040000 -0.030212 except that the "s" and "ACD0" are headers.
My question now is how I can load multiple files with that format into Matlab with their file names as variable names
So far I got:
files = dir('*.txt'); %loads all txt files
Names={};
for i=1:length(files);
Names{i} = files(i).name; %creates a cell with names
end
Names = Names';
Names_char= char(Names) %turns the names into char so I can use them as input
for i= 1: length(files);
eval ([dlmread(Names_char(i,:),'\t', 1)]);
end
however i always receieve ??? Undefined function or method 'eval' for input arguments of type 'double'
Alternatively I tried
files = dir('*.txt');
Names={};
for i=1:length(files);
Names{i} = files(i).name;
end
Names = Names';
Names_char= char(Names)
for i= 1: length(files);
eval (['M' dlmread(Names_char(i,:),'\t', 1)]);
end
However I get ??? Error using ==> horzcat CAT arguments dimensions are not consistent.
Do you have any ideas/suggestions how I could turn my text files into variables with the same name as the files?
Thanks
Ben
2 Comments
Please, format your post using [{}Code] in the editor when relevant, so the code is readable.
Also, note that building variable names dynamically is almost never a good idea. It is generally better to save data in a cell array and file names (in your case) in another cell array, with matching IDs. Another option is to use a mapping or a Java hash table.
We can discuss your code and the options that I mentioned once you have formatted your post.
Ben
on 18 Oct 2013
Accepted Answer
More Answers (1)
dpb
on 18 Oct 2013
0 votes
As Cedric has already hinted, you really, Really, REALLY don't want to do this...see
for alternatives.
There are questions regularly on how to get past other problems created by having done just what you're about to do if don't use another method. Just within the last few days we've had a long discussion with another poster who dug himself a hole he can now get out of only w/ great difficulty.
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!