简体   繁体   English

Matlab中的逻辑索引-需要帮助以加快速度

[英]Logical indexing in matlab - need help to make faster

This is what I am trying to do, created a random array to demonstrate: 这就是我想要做的,创建了一个随机数组来演示:

% 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

The above code takes a lot of time as I am dealing with a very large array , Is there a way to eliminate the for loop, meaning, instead of doing Boolean indexing element by element - can I do it for the whole array at once ? 上面的代码在处理一个非常大的数组时需要花费大量时间,有没有一种方法可以消除for循环,这意味着可以代替逐个元素地进行布尔索引-我可以一次对整个数组进行处理吗?

This will run x2.5 faster, anyway, array is too big so it still takes 0.3s per loop, so 160000 loops is like 13 hours on single cpu. 无论如何,这将运行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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM