Assign the same variable to all elements of a Matrix

13 views (last 30 days)
I would like to assign a variable to all elements of a Matrix without using a for loop to obtain a matrix M such that : M(nxn) = [x , x, x , x ,x ... ].
In my particular case x is an sdpvar and M is a matrix I use to set up the constraints of an optimisation problem.
Thank you

Answers (2)

Matt J
Matt J on 8 Nov 2021
I haven't worked with YALMIP, but can't you do
M=sdpvar(n);
M(:)=x;
  1 Comment
Adil Bendouro
Adil Bendouro on 8 Nov 2021
That is what I initially tried to do but it doesn't seem to work when the variables are multidimensional.
In my case I have:
M = sdpvar(10,10,10);
x = sdpvar(10,1);
M(:,:,:) = x;
which gives: In an assignment A(I) = B, the number of elements in B and I must be the same.

Sign in to comment.


John D'Errico
John D'Errico on 8 Nov 2021
As with Matt, I have not used the code, but this should work.
M = repmat(sdpvar(1,1),[10 10 10]);
  1 Comment
Adil Bendouro
Adil Bendouro on 9 Nov 2021
Unfortunately repmat didn't work for me. I believe that it is because it assigns copies of the variable x instead of the actual variable. Therefore the constraints of my linear program are not applied to x, which makes the optimisation problem unbounded.

Sign in to comment.

Categories

Find more on Operating on Diagonal Matrices 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!