A compact way to find elements of an array which are greater, equal, or less than the elements of a second array

조회 수: 4 (최근 30일)
Hi, I have two arrays a1 and a2 and I would like to get a third array b which indicates me which elements of a1 are greater, equal or less than the elements of a2. I would indicate the elements of b with 1, 0 and -1 if the elements of a1 are greater, equal or less than the elements of a2, respectively.
% input
a1 = [0 4 7 8 1 2 3]';
a2 = [4 4 6 9 9 1 1]';
% method
b = (a1>a2);
b = double(b);
b(b==0) = -1; % assign "-1" to the elements of a1 which are less than the elements of a2
c = (a1==a2);
b(find(c==1)) = 0 % assign "0" to the elements of a1 which are equal to the elements of a2
% output
b =
-1
0
1
-1
-1
1
1
Is there any, better/more compact way, maybe in a couple of lines of code to get the same result?

채택된 답변

Voss
Voss 2022년 1월 20일
a1 = [0 4 7 8 1 2 3]';
a2 = [4 4 6 9 9 1 1]';
b = sign(a1-a2)
b = 7×1
-1 0 1 -1 -1 1 1

추가 답변 (1개)

Star Strider
Star Strider 2022년 1월 20일
To check all the elements against each other —
a1 = [0 4 7 8 1 2 3]';
a2 = [4 4 6 9 9 1 1]';
Check = sign(a1 - a2.') % R2016b & Later Releases
Check = 7×7
-1 -1 -1 -1 -1 -1 -1 0 0 -1 -1 -1 1 1 1 1 1 -1 -1 1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 -1 0 0 -1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 1 1
Check = bsxfun(@(a1,a2)sign(a1-a2), a1, a2.') % All Releases
Check = 7×7
-1 -1 -1 -1 -1 -1 -1 0 0 -1 -1 -1 1 1 1 1 1 -1 -1 1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 -1 0 0 -1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 1 1
.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by