How to create a matrix such that all the row elements add up to 1 and the column elements add up to 1?

Hi,
I'd like to create a NXN matrix, such that each of the row elements add up to 1 and each of the column elements add up to 1 as well. I'd like to create that matrix by specifying a vector that has N elements. For instance if I want to create a 5X5 matrix, I'd like to specify the elements {.4,.2,.1,.1,.2} and arrange them in a 5X5 matrix with each row and each column summing up to 1. I know MATLAB has a "magic" matrix command, but that also imposes an additional constraint that the diagonal elements add up to 1. I want to get rid of that constraint, as it only gives 1 unique matrix per N.
I'd appreciate any help regarding this problem. Thanks, Lakshmi

 Accepted Answer

First off, sanity check: if the sum of the element is not 1, and the elements must be used as-is, then error out.
If that passes, then construct the first row as any permutation of the elements. Then construct the other rows as successive circular shifts of the first row.
The "successive" circular shifts can be relaxed: as long as all of the circular shifts from 0 to N-1 are present as rows, the sums will work out.

2 Comments

x = [.4,.2,.1,.1,.2]; %x
n = numel(x); %how many x?
arow = x(randperm(n));
shiftvals = randperm(n) - 1;
p = zeros(n, n);
for K = 1 : n
p(K,:) = circshift(arow, [0 shiftvals(K)]);
end

Sign in to comment.

More Answers (2)

Your comment on the constraint making only one unique matrix is not true.
If:
x = magic(5);
then
x'
flipud(x)
fliplr(x)
circshift(x,[1 2])
Are all different and all have columns and rows that sum to the same values. I would take this, above information, do something with it to make MATLAB's magic square randomized and then use it to index into x.
x = [.4,.2,.1,.1,.2]; %x
n = numel(x); %how many x?
p = x(circshift(mod(magic(n),n)+1,randperm(n,2))); %a random selection
Check:
sum(p)
sum(p,2)
Thanks Sean for the code. I ran the code and it works. I have never used circshift before and thanks for introducing me to that function, seems quite useful.
Lakshmi

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!