Reputation: 345
Even if many subjects have the same topics, I don't find my answer.
I have something like 30 .txt files in a folder (with a different names), I would like to import all of them in MATLAB. Take a column from each file and make a vector with all those columns.
Bombo30m1.txt
Bombo30m2.txt
Bovolon30m2.txt
Rigutti30m4.txt
Each .txt file have 45 columns of number separated by comma. All the numbers inside my text files are integers.
All files have the same number of columns, but not the same numbers of row (more or less 4000 for each).
For all of the files, I would like to take the column 40 and make one vector with it. So I will get a big vector.
Upvotes: 0
Views: 419
Reputation: 14939
First, create a struct with all the file information:
dir('*.txt')
gives you a struct with all information about the files:
4x1 struct array with fields:
name
date
bytes
isdir
datenum
Define a variable where you'll place the values of the first columns
Use number_of_files = numel(filenames)
to get the number of files. col_values
is the vector you will place the values in. Note, you should try to pre-allocate memory.
filenames(1).name
gives you the name of the first file, "Bombo30m1.txt".
Loop through all files, and get the values out: load(filenames(ii).name)
.
And finally place the new values after the previous ones in col_values
.
To sum it all up:
filenames = dir('*.txt');
number_of_files = numel(filenames);
col_values = [];
for ii = 1:number_of_files
all_values = load(filenames(ii).name);
col_values = [col_values; all_values(:,1)];
end
NOTE!! This code contain some sub-optimal code, as I've created a growing vector inside the loop. If this is a procedure that will be performed many times, then you should rewrite it a bit. Relevant
Upvotes: 1