Counting occurences of each number in a column when it's equal to all numbers in the same line?
조회 수: 1 (최근 30일)
이전 댓글 표시
I have, for example, the following matrix P:
1 2 3
2 2 2
3 3 3
4 4 1
4 4 4
2 2 2
1 4 2
How can I count the occurences of each number in the first column, only when it's equal to all numbers in the same line? For this example, the result would be:
0
2
1
1
I've tried something like this:
alpha = unique(P);
O = zeros(size(alpha));
for k = 1 : length(alpha)
O(k) = sum(P(:,1) == alpha(k));
end
which counts the occurences for the first column of P, but I don't know how to exclude the cases where the line isn't all the same number. How should I alter my code?
댓글 수: 0
답변 (2개)
KALYAN ACHARJYA
2019년 10월 20일
P=[1 2 3
2 2 2
3 3 3
4 4 1
4 4 4
2 2 2
1 4 2];
[r c]=size(P);
for i=1:r
if range(P(i,:))==0
data=ismember(P,P(i,:),'rows');
result(i)=sum(data);
else
result(i)=0;
end
end
result'
Result:
ans =
0
2
1
0
1
2
0
댓글 수: 0
Image Analyst
2019년 10월 20일
Try this:
P=[1 2 3
2 2 2
3 3 3
4 4 1
4 4 4
2 2 2
1 4 2];
allTheSame = P(:, 1) == P(:, 2) & P(:, 1) == P(:, 3) % Rows where all 3 values are the same.
counts = histcounts(P(allTheSame, 1), 1:max(P)+1)
You'll see
allTheSame =
7×1 logical array
0
1
1
0
1
1
0
counts =
0 2 1 1
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!