如何在matlab中加速双循环

时间:2015-01-24 13:21:02

标签: performance matlab for-loop matrix vectorization

这是this question的后续问题。

以下代码需要花费大量时间才能完成。你对加快这个过程有什么建议吗?变量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英特尔i5和16 GB DDR3的iMac上运行MatLab R2014b。

1 个答案:

答案 0 :(得分:5)

您可以在此处使用 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.