# How to define cvx variable in loop?

I have K matrices where all of them are M*M and symmetric semidefinite. How I can define these matrices as cvx variables using a loop?

For K=3, I use this:

variable w1( M ,M) symmetric semidefinite

variable w2( M ,M) symmetric semidefinite

variable w3( M ,M) symmetric semidefinite

But I would love to do this in a loop like:

for k=1:K
W{k} == variable(M ,M) symmetric semidefinite;
end

However, Tthis is not valid in Matlab!

Could anybody help me please? Thanks!

The problem is every time I change the value of K in my matlab code, I need to change w1âŚwK! Many thanks in advance!

`variable W(M,M,K) semidefinite`

W(:,:,i) will be semidefinite for each i from 1 to k. No for loop required. See How to change the number of variables based on the iteration number? .

1 Like

Thanks a million Mark! Could you please kindly let me know if I could use:

``````    w_obj = 0;
for k=1:K
w_obj = trace( W(:,:,k));
end
minimize (w_obj)
``````

For example, for K=4, what I want to minimize is:
minimize (trace( W( : ,:,1))+trace( W( : ,:,2))+trace( W( : ,:,3))+trace( W( : ,:,4)))

`w_obj = w_obj + trace( W(:,:,k));`
Your code (without my change) would be minimizing `trace( W(:,:,K))`