How to find the frequency of each row with certain coordiante in a matrix?

3 次查看(过去 30 天)
Hello all,
I have an mx2 matrix with its rows (0,1), (-1,0), (0,1), (0,-1), (1,1), (-1,1), (1,-1),(-1,-1); I would like to find the frequency of each of above coordinates. In other words, if I have A=[1 1;0 1;-1 1;1 0;-1 1], I would like to get something like,
number of times that (1,1) has appeared=1; number of times that (0,1) has appeared=1; number of times that (-1,1) has appeared=2; number of times that (1,0) has appeared=1; number of times that (0,-1) has appeared=0; number of times that (-1,-1) has appeared=0; number of times that (-1,0) has appeared=0; number of times that (1,-1) has appeared=0;
when I use "find" command I get an error. Thank you.

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2014-3-29
编辑:Azzi Abdelmalek 2014-3-29
A=[1 1; 0 1; 1 0; -1 1;-1 1;0 1;0 1]
[ii,jj,kk]=unique(A,'rows','stable')
f=histc(kk,1:numel(jj)); % Frequency
result=[ii f]
  3 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2014-3-29
编辑:Azzi Abdelmalek 2014-3-29
Ok use this (without stable option), maybe you have an old version of Matlab
A=[1 1; 0 1; 1 0; -1 1;-1 1;0 1;0 1]
[ii,jj,kk]=unique(A,'rows')
f=histc(kk,1:numel(jj)); % Frequency
result=[ii f]

请先登录,再进行评论。

更多回答(1 个)

Aditya Rathore
Aditya Rathore 2022-2-1
There are two things:
  1. Your row length is small (2)
  2. You want to also retrieve the stored values
I suggest you make a matrix for storing frequencies
freqs = zeros(m, 2);
[rows, ~] = size(A);
for idx=1:rows
i = A(idx, 1);
j = A(idx, 2);
freqs(i+2,j+2) = freqs(i+2, j+2) + 1; %Because you have -1 also
end
When retrieving a value, simply do
count = A(i+2, j+2);
This approach is useful as you can normalize the counts and get probability using
freqs = freqs / sum( freqs, 'all');
I tried it for image based task in RGB space and found this to be fastest solution.

标签

Community Treasure Hunt

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

Start Hunting!

Translated by