# CVX in a parallel loop

CVX is a really efficient tool for me. Now, I want to use CVX in a parallel loop in matlab, for example

``````parfor ipeak = 1:t
X_wh = A(:,:,ipeak); ZC = B(:,ipeak);  beta = C;
cvx_begin quiet
variable Atemp(n)
minimize( norm( ZC * Atemp - X_wh(:) , 2 ) + beta*norm(Atemp,1) )
subject to
Atemp >= zeros(n,1)
cvx_end

end
``````

However, matlab give the error code:

``````Attempt to add "cvx_problem" to a static workspace.
See MATLAB Programming, Restrictions on Assigning to Variables for details.

Error stack:
cvx_begin.m at 41
tensor_BCGremove_sparsepar>(parfor body) at 102
``````

Is it possible to use CVX in a parallel loop? If yes, please show me a demo; if no, do you have any alternative solutions ?

1 Like

Unfortunately, CVX cannot be used in a parallel loop. I have been investigating it, but it will require a non-zero financial expense for me to implement it. Thus it is likely to happen, but only when a commercial client is willing to pay for it

well I used cvx in parfor but it sometimes shows unexpected results. for example when I use ‘parfor’ it returns NaN for some special input parameters, while if I use ‘for’ for the same problem it return valid answer. I dont know what is the reason.however for other input parameters it return the same valid answer for both of ‘for’ and ‘parfor’.

Dear wch,
I have similar problem, but comes out with different error: Undefined function or variable “Atemp”.

Basically I tried to get optimal value of L2norm+L1norm using networkSamples (node=40, samplesize=25) to recover the network. Could you help me this problem? since the node is usually very big, parallel computing would be great if parfor works.

``````function q=quad_fun(networkSamples, C)
t=40
parfor ipeak = 1:t
ZC = networkSamples(:,ipeak);  beta = C;
cvx_begin quiet
variable Atemp(n)
dotproduct = networkSamples * Atemp(:);
minimize( norm( ZC * Atemp - dotproduct , 2 ) + beta*norm(Atemp,1) )
subject to
Atemp(ipeak)==0
cvx_end

end``````

I usually run cvx in parfor without any problem. But first you should define a function that contains the cvx code then call it into the parfor loop.

here is an example to compute an error using monte carlo simulation

``````function r=Estimate_x(A,y,x,n)

cvx_solver sdpt3
cvx_begin quiet
variable v(n);
minimize (norm(v,1));  % estimate vector x using l_1 minimization
subject to
y-A*v==0;
cvx_end
r=norm(x-v);  %compute the error.
end
``````

Then your main code will be as follow:

``````m=7;
n=10;
k=4;
A=randn(m,n);
x=zeros(n,1);
sp=randn(k,1);
rp=randperm(n);
x(rp(1:k))=sp;