2017-08-22 57 views
0

這就是我要做的,創建一個隨機的陣列來演示:邏輯索引 - 需要幫助以做出更加快速

% all IDs 

all_IDS = 1:216000000;  

% Array 1 

X = round(1550*rand(216000000,1)); 
Y = round(1550*rand(216000000,1)); 
Z = round(90*rand(216000000,1)); 

% Array 2 

Xsub = round(1550*rand(160000,1)); 
Ysub = round(1550*rand(160000,1)); 
Zsub = round(90*rand(160000,1)); 

del_val =1; 

% required o/p 
reqd_op = zeros(1,10); 

% boolean indexing 
indx =1; 
for jj = 1:160000 

    VID_X = Xsub(jj); 
    VID_Y = Ysub(jj); 
    VID_Z = Zsub(jj); 

    I2 = (X>VID_X-del_val & X<VID_X+del_val)& (Y>VID_Y-del_val & Y<VID_Y+del_val) & (Z>VID_Z-del_val & Z<VID_Z+del_val); 

    len = numel(all_IDS(I2)); 

    reqd_op(1,indx:indx+len-1) = all_IDS(I2); 
    indx=indx+len; 
end 

上面的代碼需要花費大量的時間,因爲我處理一個非常大的數組,是否有一種方法可以消除for循環,這意味着,而不是按元素進行布爾索引 - 我可以一次完成整個數組嗎?

+2

見[什麼是XY-問題以及如何避免它(https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) –

+2

參見[線性索引,邏輯索引和所有](https://stackoverflow.com/q/32379805/5211833) – Adriaan

+1

btw你的循環只保留在最後是'jj'的最後一個迭代,它是'I2 =(X> Xsub (160000)-del_val&X Ysub(160000)-del_val&Y Zsub(160000)-del_val&Z

回答

1

這將運行x2.5更快,無論如何,數組太大,所以它仍然需要0.3s每循環,所以160000循環就像單CPU的13個小時。

if ~exist('X','var') 
    % Array 1 
    X = round(1550*rand(216000000,1,'single')); 
    Y = round(1550*rand(216000000,1,'single')); 
    Z = round(90*rand(216000000,1,'single')); 
    % Array 2 
    Xsub = round(1550*rand(160000,1,'single')); 
    Ysub = round(1550*rand(160000,1,'single')); 
    Zsub = round(90*rand(160000,1,'single')); 
end 

del_val =single(1); 
reqd_op = zeros(1,10,'single');% required o/p 

tic 
index =1; 
for jj = 1:10 
    VID_X = Xsub(jj); 
    VID_Y = Ysub(jj); 
    VID_Z = Zsub(jj); 
    IdxFinal=[]; 
    Idx1=find(abs(X-VID_X)<del_val); %little better than X>VID_X-del_val & X<VID_X+del_val) 
    if ~isempty(Idx1) 
     Idx2 = Idx1(Y(Idx1)>VID_Y-del_val & Y(Idx1)<VID_Y+del_val); 
     if ~isempty(Idx2) 
      Idx3= Idx2(Z(Idx2)>VID_Z-del_val & Z(Idx2)<VID_Z+del_val); 
      IdxFinal=Idx3; 
     end 
    end 
    len = length(IdxFinal); 
    index=index+len; 
    if len>0 
     reqd_op(1,index:index+len-1) = IdxFinal; 
    end 
end 
toc