Reputation: 702
I have some .csv files in a directory and I would like to create a cell array in which every cell is a cell array containing the data of one .csv file.
For example, one of my .csv files named example.csv
could be like this:
126; 1; d; 0.0238343
10; 1; d; 8.05893e-08
48; 1; d; 0.000204261
8; 1; d; 3.02726e-08
20; 1; d; 2.17914e-07
41; 1; d; 0.000179662
75; 1; d; 0.00204058
0; 1; d; 2.98228e-17
81; 1; d; 0.00241941
17; 1; d; 4.04806e-06
128; 1; d; 0.0141687
The first two columns always contain integers (the second one can have only 1 or 0), the third contains always a single character (it can be either d
or p
) and the fourth contains only floating point numbers.
Right now this is what I do for a single file:
file = fopen('example.csv');
csv_file = textscan(file, '%s%s%s%s', 'delimiter', ';', 'CollectOutput', true);
fclose(file);
csv_file = csv_file{1};
csv_file(:,1) = num2cell( str2double(csv_file(:,1)) );
csv_file(:,2) = num2cell( str2double(csv_file(:,2)) );
csv_file(:,4) = num2cell( str2double(csv_file(:,4)) );
at the end the variable csv_file
contains a cell array like this:
[126] [1] 'd' [ 0.0238]
[ 10] [1] 'd' [8.0589e-08]
[ 48] [1] 'd' [2.0426e-04]
[ 8] [1] 'd' [3.0273e-08]
[ 20] [1] 'd' [2.1791e-07]
[ 41] [1] 'd' [1.7966e-04]
[ 75] [1] 'd' [ 0.0020]
[ 0] [1] 'd' [2.9823e-17]
[ 81] [1] 'd' [ 0.0024]
[ 17] [1] 'd' [4.0481e-06]
[128] [1] 'd' [ 0.0142]
How can i do this for every .csv file in my directory in such a way that in the end I end up with a single variable containing all the cell arrays?
I need this so then I can work on all the cell arrays as I want, without the need to extract them into a variable all the time.
Upvotes: 1
Views: 67
Reputation: 19689
This is what suggested to you in the comments:
filename=dir; %attributes
filename={filename.name}; %Extracting filenames
len=length(filename); %Number of files
files = cell(1,len ); %Pre-allocation
for m=1:len
file = fopen(filename{k});
csv_file = textscan(file, '%s%s%s%s', 'delimiter', ';', 'CollectOutput', true);
fclose(file);
%Your array manipulations
csv_file = csv_file{1};
csv_file(:,1) = num2cell( str2double(csv_file(:,1)) );
csv_file(:,2) = num2cell( str2double(csv_file(:,2)) );
csv_file(:,4) = num2cell( str2double(csv_file(:,4)) );
files{m}= csv_file; %Saving result of each iteration in an index of a cell array
end
Upvotes: 1