有没有办法使这段代码更快,如果可能的话,避免循环



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

目标是找到:计数器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% 计算时间的解决方案!并且没有错误消息:内存不足

看看这对你来说是如何工作的 -

%// 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))

如果不真正解释代码,就很难确定你的代码实际上应该完成什么。但是,我会给它一个破解:

% 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

最新更新