最近用到cvx工具箱來求解稀疏問題,大家都知道,cvx工具箱運行起來非常慢,所以想用parfor命令來執行並行運算,提高效率,但是直接在parfor裏寫cvx_begin會報錯
錯誤使用 cvx_begin (line 41) 可見性違例錯誤。 請參閱確保 parfor 循環或 spmd 語句中的可見性。
經過查閱資料,發現這樣可以解決問題
將
cvx_begin
cvx_end
寫爲一個單獨的function,然後直接在parfor裏調用這個子函數即可
例如
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
然後主函數的代碼寫爲:
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;
y=A*x; % define your model
parfor k=1:100 %Monte Carlo Simulation for 100 iterations
e(k)=Estimate_x(A,y,x,n);
end
error=mean(e);
參考資料
http://ask.cvxr.com/t/using-cvx-with-gpu-parallel-computing/4862/2