Counting occurences of each number in a column when it's equal to all numbers in the same line?
1 view (last 30 days)
Show older comments
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 Comments
Answers (2)
KALYAN ACHARJYA
on 20 Oct 2019
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 Comments
Image Analyst
on 20 Oct 2019
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 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!