Count the occurence certain elements based on condition in next column

Hello.
I have a matrix consists of A = [ 1 3 2 2 4 1 2 3 4 1 3] and B = [0 0 -3 0 2 1 4 0 0 -2 0]
How can I determine the occurence of element in A when corresponding value in B is not 0:
C = [
1 2
2 2
3 0
4 1]
Please help me..
Really appreciate it!!

 채택된 답변

U=unique(A(:));
[~,J]=ismember(A(B~=0),U);
n=accumarray(J(:),1,size(U));
C=[U,n]

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 11월 3일
편집: Ameer Hamza 2020년 11월 3일
Try this
A = [1 3 2 2 4 1 2 3 4 1 3];
B = [0 0 -3 0 2 1 4 0 0 -2 0];
C = [1:max(A); histcounts(A(B~=0), 'BinMethod', 'integers')].'

댓글 수: 9

Woww.. Thank you very much. Exactly what I need!!
I am glad to be of help!!!
Daniar Fahmi
Daniar Fahmi 2020년 11월 4일
편집: Daniar Fahmi 2020년 11월 4일
Hi..
Is there any limitation for histcounts function? because when I used it in larger data (near 2 x 60M) and then it was found that unique element (vector A) was 360 data, the result of histcounts was only 300 data
Can you share your data in a .mat file?
Following solution will be more robust
A = dataPD(1,:);
B = dataPD(2,:);
C = [1:max(A); histcounts(A(B~=0), 0.5:1:max(A)+0.5)].'
thanks.. It works!!!
Bruno Luong
Bruno Luong 2020년 11월 4일
편집: Bruno Luong 2020년 11월 4일
Attention A of your data contains 82335 0s and they are discarded from counting
Yeah. I have just realised it..

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

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

질문:

2020년 11월 3일

댓글:

2020년 11월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by