MATLAB: Main diagonal operations problem

diagidentity matrixMATLAB

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

Best Answer

Using Roger Stafford's FEX submission randfixedsum (must be downloaded first):
>> N = 4; % matrix size
>> M = nan(N,N); % preallocate
>> V = 0.3+(1-0.3)*rand(1,1) % diagonal value
V =
0.47505
>> M(~eye(N)) = randfixedsum(N-1,N,1-V,0,1); % other values
>> M = M.'; % transpose
>> M(1:N+1:end) = V % assign diagonal value
M =
0.47505 0.40657 0.0087969 0.10958
0.12917 0.47505 0.21287 0.1829
0.35794 0.15519 0.47505 0.011825
0.41335 0.032696 0.078907 0.47505
Checking the sum of each row:
>> sum(M,2)
ans =
1
1
1
1
and diagonal:
>> diag(M)
ans =
0.47505
0.47505
0.47505
0.47505