文本可以使用的速度增加



我编写了一个程序,该程序接受一个.csv文件,并将每个文件的第三列堆叠在512x512xNumberOfFiles单元格数组的适当的第三维中。代码是这样的:

[filenames,filepath] = uigetfile('*.csv','Opening the data files','','Multiselect','on');
filenames = fullfile(filepath,filenames);
NumFiles = numel(filenames);
Pixel = cell(512,512,NumFiles);
count=0;
num_pixels = size(Pixel,1)*size(Pixel,2);
for k = 1:NumFiles
    fid = fopen(char(filenames(k)));
    C = textscan(fid, '%d, %d, %d','HeaderLines',1);
    Pixel(count + sub2ind(size(Pixel),C{1}+1,C{2}+1)) = num2cell(C{3});
    count = count + num_pixels;
    fclose(fid);
end

这里的textscan调用打开每个文件大约需要0.5 +/- 0.03s(这是262144 (512x512)个数据长),sub2ind调用每个文件大约需要0.2 +/- 0.01s。

有没有办法减少这个时间,或者这似乎是运行代码的最优方式?我每次将处理大约1000个文件,因此等待8-9分钟才能获得正确的数据似乎有点过分(考虑到我还没有将其用于其他任何事情)。

提示吗?

希望这将导致一些改进,仍然保持它与textscan。此外,确保值看起来不错。

[filenames,filepath] = uigetfile('*.csv','Opening the data files',...
    '','Multiselect','on');
filenames = fullfile(filepath,filenames);
NumFiles = numel(filenames);
PixelDouble = NaN(512*512,NumFiles);
for k = 1:NumFiles
    fid = fopen(char(filenames(k)));
    C = textscan(fid, '%d, %d, %d','HeaderLines',1);
    PixelDouble(:,k) = C{3};
    fclose(fid);
end
Pixel = num2cell(permute(reshape(PixelDouble,512,512,[]),[2 1 3]))

我必须鼓励你遵循这个问题-最快的Matlab文件阅读?这就是答案

最新更新