필터 지우기
필터 지우기

reduce time taken to execute nested for loop

조회 수: 1 (최근 30일)
krs.rb1
krs.rb1 2011년 10월 17일
Hi,
I am trying to subtract two matrix. and my program is as follows :
for i=1:length(B)
for j=1:length(A)
Y(j,:)=B(i,:)-A(j,:); %(takes one row of B and subtracts it with each row of A)
end
end
Now the inner for loop takes about 0.37 seconds. But my matrices are huge A[7000,100] & B[4000,1000]. Hence the above nested for loop takes about half hour+ to execute completely. Can anyone please suggest a much faster way to do the same. (hopefully in a minute or two)
  댓글 수: 1
krs.rb1
krs.rb1 2011년 10월 17일
well i tried ,
[i1, j1] = meshgrid(1:size(B,1),1:size(A,1));
Y = minus(B(i1,:),A(j1,:));
but it gave an error :
??? Out of memory. Type HELP MEMORY for your
options.
did i do something wrong?
and,I had made a mistake, it's -> A[7000,1000] & B[4000,1000]

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2011년 10월 17일
1. Pre-allocate the output! 2. Relying on LENGTH to reply the wanted dimension is prone to errors. Use SIZE(X, dim) instead.
lenA = size(A, 1);
lenB = size(B, 1);
Y = zeros(lenA, lenB);
for i = 1:lenB
for j = 1:lenA
Y(j,:) = B(i,:) - A(j,:);
end
end
Now the values of Y are overwritten completely in every iteration of the for i loop. Most likely this is not intented. If this problem is fixed, you can try if BSXFUN or manual expansion by ONES is faster instead of the inner loop:
Y = bsxfun(@minus, B(i, :), A);
% Or:
Bi = B(i, :);
Y = Bi(ones(1, lenA), :) - A;

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by