Reducing the computation time using a for loop

조회 수: 1 (최근 30일)
Danielle Leblance
Danielle Leblance 2016년 10월 11일
편집: Guillaume 2016년 10월 11일
A is a matrix with a bigger size than the B matrix. B is a subset of A (except the last column that I am trying to fill A;s last column with the respective values of B's last column). I wrote the following loop that has been running for more than an hour although it should be simple. I hoe someone can help me to reduce the computation time:
for m=1:size(A,1)
for n=1:size(B,1)
x0a=A(:,2)==B(n,2) & A(:,1)==B(n,1);
if ~isempty(x0a)
A(m,end)=B(x0a,end);
end
end
end

채택된 답변

Guillaume
Guillaume 2016년 10월 11일
편집: Guillaume 2016년 10월 11일
You do not need a loop at all if you use ismember:
[isinB, Brow] = ismember(A(:, [1 2]), B(:, [1 2]), 'rows');
A(isinB, end) = B(Brow(isinB), end);
edit: silly typo
  댓글 수: 2
Danielle Leblance
Danielle Leblance 2016년 10월 11일
I am receiving an error Index exceeds matrix dimensions.
Error in AvgA (line 7) [isinB, Brow] = ismember(A(:, [1 2]), B(:, [1 2], 'rows'));
Guillaume
Guillaume 2016년 10월 11일
You corrected my typo, but not correctly. The missing closing bracket was supposed to go at the end of B(:, [1 2]).
I've now fixed it in my answer.

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

추가 답변 (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