2
votes

What I want to do

I want to create a program that generates a random matrix nxn (2D array) on which I have to make calculations whose elements are symmetric to its main diagonal and the sum of each row equals to 1.

Details

I have tried too many algorithms but no one is working properly, I can do the matrix symmetric by typing

for i=1:n
    n=rand(100);

    for j=1:n

       if(j>i)
          matrix(i,j) = rand(100);
          matrix(j,i)=matrix(i,j);
       else if (j==i)
         matrix = rand(100);
       end
    end
end

I can do also the sum of the row of the matrix equal to 1 by finding the sum on each row and then dividing each element with the sum of that row, and then when I make the sum of the row it equals 1

for i=1:n

    for j=1:n
       matrixS(i,j) = matrix(i,j)/sum(i); % The vektor of the row sums is made by another algorithm
    end
end

Issue

The problem is when I want to make this array with all the characteristics I mentioned, each row equals 1 and the matrix is symmetric by the main diagonal

Any ideas?

1
You want the random matrix or you want a random matrix with specific values (it's not random any more)? I don't understand the problem here.hesar
Hesar thnx for your question! The idea is that I want to generate a matrix that has these specifics : Symmetric referred to the main diagonal and each row of this matrix has the sum equal to 1.E-Riddie
When you say "random", you need to specify the distribution that you want (uniform?)Luis Mendo
By the word random I mean the numbers in this matrix are choosen randomly for the elements over the main diagonal see the question with code 1 (j>i)E-Riddie

1 Answers

2
votes

If that's sufficiently random, you can generate a symmetric matrix with random off-diagonal elements and then adjust the diagonal so that the row (and column) sums equal 1.

n = 4;
randMat = zeros(n);
randMat(tril(true(n),-1)) = rand( n*(n-1)/2, 1); %# fill in some values
randMat = randMat + randMat'; %# make symmetric
randMat(eye(n)>0) = 1 - sum(randMat,2); %# adjust diagonal

%# Example

randMat =

   -0.7829    0.2785    0.5469    0.9575
    0.2785   -0.4010    0.9649    0.1576
    0.5469    0.9649   -1.4824    0.9706
    0.9575    0.1576    0.9706   -1.0857

>> sum(randMat)  %# the same as sum(randMat,2)'

ans =

    1.0000    1.0000    1.0000    1.0000