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

时间:2015-03-09 17:25:18

标签: performance matlab loops matrix runtime

A1B1C1A2B2C2 6 矩阵相同尺寸4435X2000

我必须找到ijk的值A1(k,2000) == A2(i,j)B1(k,2000) == B2(i,j)C1(k,2000) == C2(i,j),条件{ {1}}和X(k)==1

目标是找到:计数器 L T D

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

Y(i,j)==1

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

2 个答案:

答案 0 :(得分:1)

确定代码实际应该完成的内容非常困难,而无需真正解释代码。但是,我会给它一个解决方法:

% 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

答案 1 :(得分:1)

了解这对您有何影响 -

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