How to compare two array in nested loop ?

조회 수: 12 (최근 30일)
Joni Saputra
Joni Saputra 2018년 11월 21일
댓글: Joni Saputra 2018년 11월 22일
I have code like this :
Ind = [];
distTh = 5;
A = [1;7;14];
B = [2;5;8;10];
for i = 1:size(A,1)
for j = 1: size(B,1)
Distance = abs(B(j) - A(i));
if Distance < distTh
Ind = [Ind j];
end
end
end
My questions : How to make elements in array 'B' no longer compared to array 'A' (remove index 'B'), if it is already in 'Ind' ?
Thank you very much.

채택된 답변

Geoff Hayes
Geoff Hayes 2018년 11월 21일
Joni - well you can use find or ismember to check to see whether you should add j to the list of indices Ind as
if Distance < distTh && ~ismember(j, Ind)
Ind = [Ind j];
end
or use a similar check to skip the compare altogether
for i = 1:size(A,1)
for j = 1: size(B,1)
if ~isempty(find(Ind == j))
continue;
end
Distance = abs(B(j) - A(i));
if Distance < distTh
Ind = [Ind j];
end
end
end
There are probably other ways to solve this too. Can you give us an idea as to how large your A and B matrice might be? (As this will impact performance and help you decide which method to use (find vs ismember, etc.).

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by