Main diagonal operations problem
Show older comments
Hi guys, I need your help.
I want to create a matrix(4,4) in which the main diagonal have values between 0.3 and 1 and the other cells assume values such as to have a horizontal sum equal to 1.
By now I'm using the following code but the only result is to have a main diagonal composed by the same numbers:
x = eye(4)
x(1,1) = 1+(0.3-1)*rand(1,1)
x(2,2) = x(1,1)
x(3,3) = x(1,1)
x(4,4) = x(1,1)
Any suggestion?
PS : I've tried even with diag
2 Comments
"...the other cells assume values such as to have a horizontal sum equal to 1"
Are there any other requirements on the other elements? Positive, negative, fractional values, integer, >1, >100, >1e100 ... what values are allowed?
What is the "horizontal sum": do you mean to sum along the 2nd dimension (i.e. along each row) ?
Giuseppe Pintori
on 13 Sep 2019
Accepted Answer
More Answers (3)
John D'Errico
on 13 Sep 2019
Edited: John D'Errico
on 13 Sep 2019
Easy enough, it seems. First, determine the diagonal elements.
x = diag(rand(1,4)*.7 + .3);
Next, you need to choose the other row elements randomly so the sum will be 1. But that sum will now depend on the diagonal element you just chose. Stilll simple, as long as you use randfixedsum, by Roger Stafford, found on the file exchange.
for i = 1:4
x(i,setdiff(1:4,i)) = randfixedsum(3,1,1 - x(i,i),0,1)';
end
Did it work? Of course.
x
x =
0.83586 0.075979 0.057706 0.030454
0.012356 0.85664 0.11425 0.016757
0.13748 0.21163 0.43081 0.22009
0.15838 0.037488 0.16129 0.64284
>> sum(x,2)
ans =
1
1
1
1
Find randfixedsum here:
Matt J
on 13 Sep 2019
x=eye(4);
x(1:5:end)=0.7*rand(4,1)+0.3
1 Comment
Giuseppe Pintori
on 13 Sep 2019
Bruno Luong
on 13 Sep 2019
Edited: Bruno Luong
on 13 Sep 2019
Here is a method that has two advantages:
- without the need of Roger's FEX randfixedsum
- Produce matrix with rigourous uniform conditional probability
N = 4; % matrix size
% diagonal lo/up bounds
dmin = 0.3;
dmax = 1;
% random (common) diagonal value
d = dmax-(dmax-dmin)*rand().^(1/(N-1)); % Edit see comment above, equiv to rejection method
% d = dmin+(dmax-dmin)*rand;
% Generate N random vectors of length N-1 required sum == (1-d)
V = -log(rand(N-1,N)); % Marsaglia's [1961] method
V = V .* ((1-d)./sum(V,1));
% Arrange in the final matrix
A = zeros(N);
isdiag = sparse(1:N,1:N,true);
A(isdiag) = d;
A(~isdiag) = V(:);
A = A.';
% Check result
disp(A)
sum(A,2)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!