有没有办法使这段代码更快,并尽可能避免循环?

Is there a way to make this code faster and if possible avoid loops?

A1B1C1A2B2C26 具有相同维度的矩阵 4435X2000.

我必须找到 ijk 的值 A1(k,2000) == A2(i,j)B1(k,2000) == B2(i,j) 以及 C1(k,2000) == C2(i,j) ,其中条件 X(k)==1Y(i,j)==1

objective就是求:counter,L,TD

有没有办法让这段代码更快?我可以避免循环吗?

counter=0;
L(1)=0;
T(1)=0;
D(1)=0;

for k=1:4435
    if X(k)==1      % X is a vector (4435x1)
       F(k,:) = [A1(k,2000) B1(k,2000) C1(k,2000)] 
       for i=1:4435
           for j=100:1999
               if Y(i,j)==1      % Y is a matrix (4435x1999)
                  if F(k,:) == [A2(i,j) B2(i,j) C2(i,j)]
                     counter = counter+1;
                     L(counter)=k;
                     T(counter)=i;
                     D(counter)=j;
                  end 
               end
           end
       end
    end 
end

我想要一个至少可以节省 80% 计算时间的解决方案! 并且没有错误消息:内存不足

如果不真正努力解释您的代码,就很难确定您的代码实际应该完成什么。但是,我会尝试一下:

% Determine where X is true.
XTrue = X == 1;

% Extract values from A1,B1,C1 where X is true.
F ( XTrue , 1 : 3 ) = [ A1(XTrue,2000) B1(XTrue,2000) C1(XTrue,2000) ];

% Determine where Y is true.
YTrueIndex = find ( Y == 1 );

% Determine where the extracted values match
counter = [];
L = [];
T = [];
D = [];

for ( ii = 1 : length(YTrueIndex) )
  indexCurrent = YTrueIndex(ii)
  FRowsThatMatch = F(:,1)==A2(indexCurrent) & F(:,2)==B2(indexCurrent) & F(:,3)==C2(indexCurrent);

  matchCount = length ( find ( FRowsThatMatch ) );

  if ( matchCount > 0 )
    counter = counter + matchCount;

    [ i , j ] = ind2sub ( size ( Y ) , indexCurrent );
    L = [ L , find ( FRowsThatMatch ) ];
    T = [ T , ones(matchCount,1)*i ];
    D = [ D , ones(matchCount,2)*j ];
  end
end

看看这对你有何影响 -

%// Store X-Y data by calling X() and Y() functions
X_data = X(1:4435);
Y_data = Y(1:4435,100:1999);

range1 = 100:1999 %// define range for columns
A2 = A2(:,range1); %// Crop out A2, B2, C2 based on column-range
B2 = B2(:,range1);
C2 = C2(:,range1);
Y_data = Y_data(:,range1)==1;

%// Indices for dim-3
idx_X = find(X_data==1) 

%// Map X==1 onto A1, B1, C1
A1Lr = A1(X_data==1,end)
B1Lr = B1(X_data==1,end)
C1Lr = C1(X_data==1,end)

%// Setup output array to store L, T, D as single Nx3 output array
out = zeros(sum(Y_data(:))*numel(A1Lr),3);
%// Try out(sum(Y_data(:)==1)*numel(A1Lr),3)=0; instead for speed!

%// Start collecting output indices
count = 1;
for iter1 = 1:numel(A1Lr)
    [R,C] = find(Y_data & A2==A1Lr(iter1) & B2==B1Lr(iter1) & C2==C1Lr(iter1));
    nR = numel(R);
    out(count:count+nR-1,:) = [R C repmat(iter1,nR,1)];
    count = count + nR;
end
out(find(out(:,1)==0,1):end,:)=[];

%// Packup the outputs
T = out(:,1)
D = out(:,2) + range1(1)-1
L = idx_X(out(:,3))