Fra*_*ank 2 performance matlab for-loop matrix vectorization
以下代码需要花费大量时间来循环.你对加快这个过程有什么建议吗?该变量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
Run Code Online (Sandbox Code Playgroud)
我目前在带有3.2英特尔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
Run Code Online (Sandbox Code Playgroud)
%// 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
Run Code Online (Sandbox Code Playgroud)
案例#1:zas479 x 1672(num_iter = 50)
---------------------------------  With proposed approach
Elapsed time is 1.285337 seconds.
---------------------------------  With original approach
Elapsed time is 2.008256 seconds.
Run Code Online (Sandbox Code Playgroud)
案例#2:zas479 x 12000   (num_iter = 10)
---------------------------------  With proposed approach
Elapsed time is 1.941858 seconds.
---------------------------------  With original approach
Elapsed time is 2.897006 seconds.
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           147 次  |  
        
|   最近记录:  |