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

1 Ansicht (letzte 30 Tage)
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.

Akzeptierte Antwort

Azzi Abdelmalek
Azzi Abdelmalek am 29 Mär. 2014
Bearbeitet: Azzi Abdelmalek am 29 Mär. 2014
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 Kommentare
Azzi Abdelmalek
Azzi Abdelmalek am 29 Mär. 2014
Bearbeitet: Azzi Abdelmalek am 29 Mär. 2014
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]
Mnr
Mnr am 29 Mär. 2014
Thank you so much! I really appreciate your help!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Aditya Rathore
Aditya Rathore am 1 Feb. 2022
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