Counting specific element in one column corresponding to unique elements in an another column

조회 수: 1 (최근 30일)
I have two vectors a and b. I want to count how many times the value '-1' appears in b corresponding to unique elements in a. Is there an efficient way to do this without loops?
a = [1,1,1,1,1,2,2,2,2,2,3,3,4,4,4,5,5,5,5,5,5]';
b = [1,1,-1,1,-1,-1,-1,-1,1,1,-1,1,1,-1,-1,1,1,-1,-1,1,1]';
desired output:
1--2
2--3
3--1
4--2
5--2

채택된 답변

Jakob B. Nielsen
Jakob B. Nielsen 2020년 2월 20일
You can use logic indexing. Example:
length(b(a==1 & b==-1));
You get those entries from b which fulfils the condition that the corresponding index position in a must equal 1, and also that the same index position in b must equal -1.
& is logic AND - both conditions must be true to get an output. If you need a logic OR, the matlab operator is |
  댓글 수: 3
Jakob B. Nielsen
Jakob B. Nielsen 2020년 2월 20일
Other than manual work, you probably wont get out of a loop entirely. But it is a very simple one;
%where N is your highest integer of a that you want the comparison for;
N=5;
for i=1:N
output(i)=length(b(a==i & b==-1));
end
Stephen23
Stephen23 2020년 2월 20일
편집: Stephen23 2020년 2월 20일
"Other than manual work, you probably wont get out of a loop entirely"
Basic MATLAB functions like histc don't require a loop.

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

추가 답변 (1개)

Stephen23
Stephen23 2020년 2월 20일
>> a = [1;1;1;1;1;2;2;2;2;2;3;3;4;4;4;5;5;5;5;5;5];
>> b = [1;1;-1;1;-1;-1;-1;-1;1;1;-1;1;1;-1;-1;1;1;-1;-1;1;1];
>> u = unique(a);
>> n = histc(a(b==-1),u);
>> m = [u,n]
m =
1 2
2 3
3 1
4 2
5 2

카테고리

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