如何加速matlab中的双循环

How to speed up a double loop in matlab

这是的后续问题。

下面的代码需要大量的时间来循环。你对加快这个过程有什么建议吗?变量 z 的大小为 479x1672,其他变量约为 479x12000。

z = HongKongPrices;

 zmat = false(size(z));

 r = size(z,1);
 c = size(z,2);

 for k = 1:c
    for i = 5:r
        if z(i,k) == z(i-4,k) && z(i,k) == z(i-3,k) && z(i,k) == z(end,k)
            zmat(i-3:i,k) = 1 
        end
    end
 end

z(zmat) = NaN

我目前 运行 在配备 3.2 Intel i5 和 16 GB DDR3 的 iMac 上使用 MatLab R2014b。

你可以在这里使用 logical indexing 来替换 IF-conditional 语句并有一个小循环 -

%// Get size parameters
[r,c] = size(z);

%// Get logical mask with ones for each column at places that satisfy the condition
%// mentioned as the IF conditional statement in the problem code
mask = z(1:r-4,:) == z(5:r,:) & z(2:r-3,:) == z(5:r,:) & ...
                                            bsxfun(@eq,z(end,:),z(5:r,:));

%// Use logical indexing to map entire z array and set mask elements as NaNs
for k = 1:4
    z([false(k,c) ; mask ; false(4-k,c)]) = NaN;
end

基准测试

%// Size parameters
nrows = 479;
ncols = 12000;
max_num = 10;
num_iter = 10; %// number of iterations to run each approach, 
               %// so that runtimes are over 1 sec mark

z_org = randi(max_num,nrows,ncols); %// random input data of specified size  
disp('---------------------------------  With proposed approach')
tic
for iter = 1:num_iter    

    z = z_org;
    [..... code from the proposed approach ...]

end
toc, clear z k mask r c

disp('---------------------------------  With original approach')
tic
for iter = 1:num_iter

    z = z_org;
    [..... code from the problem ...]

end
toc

结果

案例 #1:z479 x 1672 (num_iter = 50)

---------------------------------  With proposed approach
Elapsed time is 1.285337 seconds.
---------------------------------  With original approach
Elapsed time is 2.008256 seconds.

案例 #2:z479 x 12000 (num_iter = 10)

---------------------------------  With proposed approach
Elapsed time is 1.941858 seconds.
---------------------------------  With original approach
Elapsed time is 2.897006 seconds.