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?

回答(2 个)

KALYAN ACHARJYA
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

Image Analyst
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

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by