how to create a symmetric binary variable matrix

2 views (last 30 days)
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.

Accepted Answer

John D'Errico
John D'Errico on 30 Jun 2019
Edited: John D'Errico on 30 Jun 2019
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.
  1 Comment
BOWEN LI
BOWEN LI on 30 Jun 2019
Thank you so much. I tried to index matrices, but as my y is used as a optimization variable. i just tried to make every single yij into a seperate optimization variable and then put them together as a optimization matrix as I showed in my question.
Yeah I think using "reshape" is a great idea. In my problem, actually the matrix should be a 30 by 30 one. Thank you!

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!