创建单元格数组的单元格数组

时间:2017-08-03 18:28:54

标签: matlab csv cell-array

我在目录中有一些.csv文件,我想创建一个单元格数组,其中每个单元格都是一个包含一个.csv文件数据的单元格数组。

例如,我的一个名为example.csv的.csv文件可能是这样的:

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

前两列总是包含整数(第二列只能包含1或0),第三列始终包含单个字符(可以是dp),第四列包含只有浮点数。

现在这就是我为单个文件所做的事情:

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)) );

最后变量csv_file包含一个像这样的单元格数组:

[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]

如何为我目录中的每个.csv文件执行此操作,最终我得到一个包含所有单元格数组的单个变量?

我需要这个,所以我可以根据需要处理所有的单元格数组,而无需一直将它们提取到变量中。

1 个答案:

答案 0 :(得分:1)

这是在评论中向您建议的内容:

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