MATLAB: How to create a matrix with the diagonals set to 10 and non-diagonals a random integer (0 to 2) where each row sums to 10 (without including diagonal)

matrices

I need to create a 15×15 matrix where the diagonals are all 10 and the numbers off the diagonal are a random integer between 0 and 2. I also need that non-diagonal numbers to sum to 10 for each row. See the below matrix, first row for an example.
M =
10 1 0 0 2 0 2 1 1 0 2 0 0 1 0
0 10 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 10 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 10 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 10 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 10 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 10 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 10 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 10 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 10 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 10 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 10 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 10 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 10 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 10

Best Answer

Here's a solution where you can change the values of matrix size, diagonal value, and non diagonal sum. Values between 0 and 2 are drawn to fill the rows. If they sum to the desired value, the row is filled. Otherwise they are redrawn, which ensures randomness.
% settings
matSize = 15;
diagVal = 10;
nonDiagSum = 10;
% Initialize matrix with diagonal filled in
targetMatrix = zeros(matSize);
targetMatrix(1:(matSize+1):end) = diagVal;
% Fill in matrix with random row that sums to nonDiagSum
i = 1;
while i<=matSize,
randValues = randi(3,1,matSize-1)-1;
if (sum(randValues)==nonDiagSum),
idx = true(1,matSize);
idx(i) = false;
targetMatrix(i,idx) = randValues;
i = i+1;
end
end
This executes quickly for your example, but it could take an exceedingly long time to execute if matSize is very different from nonDiagSum.
Hope this helps.
Related Question