Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to create a weight matrix bases on how frequent each element appear in the matrix?

Tags:

matrix

matlab

This is the input matrix

 7     9     6
 8     7     9
 7     6     7

Based on the frequency their appearance in the matrix (Note. these values are for explanation purpose. I didn't pre-calculate them in advance. That why I ask this question)

 number frequency
 6      2
 7      4
 8      1
 9      2

and the output I expect is

 4     2     2
 1     4     2
 4     2     4

Is there a simple way to do this?

like image 962
Jessada Thutkawkorapin Avatar asked Dec 28 '22 03:12

Jessada Thutkawkorapin


2 Answers

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

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

Now do:

[a m n] = unique(X);

b = hist(X(:),a);

c = reshape(b(n),size(X));

Which gives this value for c:

4     2     2
1     4     2
4     2     4

If you also wanted the frequency matrix, you can get it with this code:

[a b']
like image 158
Chris Taylor Avatar answered May 18 '23 19:05

Chris Taylor


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

weight = zeros(size(a));
for k = 1:size(freq,1)
    weight(a==freq(k,1)) = freq(k,2);
end
like image 42
yuk Avatar answered May 18 '23 19:05

yuk