MATLAB: Convert vector to matrix

binomial coefficientinverse binomial coefficientvector to matrix

i have a vector
a=[1,2,3,4,5,6];
i want to convert it to matrix such that the diagonals are all 0 and the rest of the elements are:
M=[0 1 2 3;1 0 4 5;2 4 0 6;3 5 6 0];
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0

Best Answer

>> a = [1,2,3,4,5,6];
>> M = tril(ones(4),-1);
>> M(M>0) = a;
>> M = M+M.'
M =
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
And if you want to automatically adjust the size you can basically invert the binomial coefficient:
>> N = (sqrt(1+numel(a)*8)-1)/2;
>> M = tril(ones(N+1),-1);