What is the easiest way to create weighted matrix bases of how often each element appears in the matrix?

This is the input matrix.

7 9 6 8 7 9 7 6 7 

Depending on the frequency of their appearance in the matrix (note that these values ​​are intended to explain the purpose, I did not calculate them in advance. Therefore, I ask this question)

  number frequency 6 2 7 4 8 1 9 2 

and expected result

  4 2 2 1 4 2 4 2 4 

Is there an easy way to do this?

+4
source share
3 answers

Here is a three-line solution. First prepare the input:

 X = [7 9 6;8 7 9;7 6 7]; 

Now do:

 [amn] = unique(X); b = hist(X(:),a); c = reshape(b(n),size(X)); 

What gives this value for c :

 4 2 2 1 4 2 4 2 4 

If you also need a frequency matrix, you can get it with this code:

 [a b'] 
+5
source

Here is the code with for-loop ( a is the input matrix, freq is the frequency matrix with two columns):

 weight = zeros(size(a)); for k = 1:size(freq,1) weight(a==freq(k,1)) = freq(k,2); end 
+3
source

Perhaps this can be solved without loops, but my code looks like this:

 M = [7 9 6 ; 8 7 9 ; 7 6 7 ;]; number = unique(M(:)); frequency = hist(M(:), number)'; map = containers.Map(number, frequency); [height width] = size(M); result = zeros(height, width); %allocate place for i=1:height for j=1:width result(i,j) = map(M(i,j)); end end 
+2
source

Source: https://habr.com/ru/post/1403076/


All Articles