MATLAB: How to create a symmetric binary variable matrix

symmetric binary variable matrix

Hi,
I am wondering how to get binary variable matrix that is symmetric to the diagonal. The matrix looks like this:
[y1 y2 y3 y4
y2 y3 y3 y4
y3 y3 y3 y4
y4 y4 y4 y4]
The upper and lower triangle of the matrix is the same, meaning that the corresponding element of the upper and lower half will be equaled to 1 or 0 at the same time.
I try to write code like this:
y=optimvar('y',[4,1],'Type','integer','LowerBound',0,'UpperBound',1)%create a 4 by 1 matrix [y1 y2 y3 y4]
yij=repmat(y,1,4)% replicate y into a 4 by 4 matrix that each column is y
for n=1:4
yij(n,:)=yij(n,:)
end % let each row of yij has same binary varible that the first row is all y1, second row is all y2, third is all y3,fourth is all y4.

Best Answer

You need to learn to index matrices, as you have been posting repeatedly what are virtually the same questions. Fundamentally, what you need to learn is how MATLAB stores the elements of an array.
This would work simply enough for such a small matrix.
Yij = reshape(y([1 2 3 4 2 3 3 4 3 3 3 4 4 4 4 4]),[4 4]);
For a larger matrix, you would need to be more creative, but that would depnd on the structure of the matrix.