Create a relation matrix from a sequence (Matlab)

2019-02-20 22:49发布

I have a sequence S :

  S= 'ABCD' % which means A<B<C<D

I want to convert S into a matrix M[i,j] which have to satisfy those conditions :

   M[i,j] , M[j,i] are random
   M[i,i] =0.5
   M[i,j] + M[j,i] = 1
   M[i,j] < M[j,i] % For example: if A<B then M[A,B] < M[B,A]

For example: if we have S = 'ABCD', the M matrix will be expected as follows:

      A      B    C    D
   A  o.5  0.25  0.2   0.1
   B  0.75 0.5   0.35  0.15
   C  0.8  0.65  0.5   0.4
   D  0.9  0.85  0.6   0.5

How to create that kind of above matrix from a given sequence ?

2条回答
冷血范
2楼-- · 2019-02-20 23:25

Here's another similar approach:

n = 4;
M = tril(rand(n)*0.5, -1);
P = triu(1-M.', 1);
M = M + P + eye(n)*0.5;

Result:

M =

   0.500000   0.987433   0.711005   0.944642
   0.012567   0.500000   0.782633   0.902365
   0.288995   0.217367   0.500000   0.783708
   0.055358   0.097635   0.216292   0.500000
查看更多
叛逆
3楼-- · 2019-02-20 23:29

From your question it appears you want

  • to fill the lower part of the matrix with random entries uniformly distributed on the interval (0,0.5) (so that condition 4 in your question be satisfied);
  • the upper part is then computed according to condition 3; and
  • the diagonal is determined by condition 2.

You can do that as follows:

n = 4; %// size
M = NaN(n); %// preallocate
M(1:n+1:end) = 0.5; %// fill diagonal
ind_lower = tril(true(n), -1); %// logical index for lower part
M(ind_lower) = 0.5*rand(n*(n-1)/2, 1); %// fill lower part
M_aux = NaN(n); %// auxiliary variable to fill upper part
M_aux(ind_lower) = 1-M(ind_lower).';
M_aux = M_aux.';
M(ind_lower.') = M_aux(ind_lower.'); %// fill upper part

Example result:

M =
    0.5000    0.5214    0.7573    0.5999
    0.4786    0.5000    0.9291    0.7891
    0.2427    0.0709    0.5000    0.5421
    0.4001    0.2109    0.4579    0.5000
查看更多
登录 后发表回答