Logical comparison between two tables

조회 수: 1 (최근 30일)
Khairul Nur
Khairul Nur 2021년 8월 6일
편집: Khairul Nur 2021년 8월 6일
hi, i have two tables (value_a_per_cluster and calc_distance_min) which need to do logical comparison.
value_a_per_cluster =
0 1 1 2
1 0 2 1
1 2 0 1
2 1 1 0
calc_distance_min =
1.0000 1.4142 1.4142 1.7321
1.0000 0 1.4142 1.0000
1.7321 2.0000 1.4142 1.7321
1.7321 1.4142 1.4142 1.0000
each value in both tables need to do comparison as below:
if value_a_per_cluster <= calc_distance_min returns 2 else 3, thus the result should be:
2 2 2 3
2 2 3 2
2 2 2 2
3 2 2 2
Is it possible to do it without looping each rows and columns? Please suggest any function n code without doing the loops. TQIA

채택된 답변

Dave B
Dave B 2021년 8월 6일
편집: Dave B 2021년 8월 6일
As a quick answer, yes, you just use <= to compare the two matrices
You can take the 1s and 0s that result from doing the comparison and subtract them from 3 for an easy version that gives your answer:
value_a_per_cluster =[
0 1 1 2
1 0 2 1
1 2 0 1
2 1 1 0
];
calc_distance_min =[
1.0000 1.4142 1.4142 1.7321
1.0000 0 1.4142 1.0000
1.7321 2.0000 1.4142 1.7321
1.7321 1.4142 1.4142 1.0000
];
3-(value_a_per_cluster <= calc_distance_min)
ans = 4×4
2 2 2 3 2 2 3 2 2 2 2 2 3 2 2 2
A slightly more elegant final bit, that would extend more easily to other values, might be:
isIt = value_a_per_cluster <= calc_distance_min;
result = nan(size(isIt));
result(isIt) = 2;
result(~isIt) = 3;
result
result = 4×4
2 2 2 3 2 2 3 2 2 2 2 2 3 2 2 2
  댓글 수: 1
Khairul Nur
Khairul Nur 2021년 8월 6일
편집: Khairul Nur 2021년 8월 6일
less hassle without the loop and get what i want. TQVM for the time and code.

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

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