storing value in 2D array in a parfor loop

26 ビュー (過去 30 日間)
Luqman Saleem
Luqman Saleem 2019 年 9 月 12 日
コメント済み: Luqman Saleem 2019 年 9 月 17 日
I have something like following
R = [1, 2, 3, 4, 5];
A1 = sparse(5,5);
A2 = sparse(5,5);
parfor i = 1 : size(A1,1)
A1(i,i) = R(i);
%do a lot of things to get "j"
A2(i,j) = 1;
end
This gives notorious "Error: The variable A1 in a parfor cannot be classified.". Even if I comment out first line in parfor loop, I will still get error because of A2.
Also, I can't save data in 3rd dimension i.e.
A1(:,:,i) = R(i);
because my A1 matric is sparse matrix. I need it to be sparse.
Can someone tell me any way around this error?

採用された回答

Edric Ellis
Edric Ellis 2019 年 9 月 13 日
As mentioned in the documentation, a sliced variable must have a single subscript being the loop variable (in this case i), and the other subscripts must be constant. In this case, the simplest way to fix things is to assign to a complete row or column, like this:
R = [1, 2, 3, 4, 5];
A1 = sparse(5,5);
A2 = sparse(5,5);
[r,c] = size(A1);
parfor i = 1:r
% Fix assignment into A1:
% Build a sparse row with the value in the right place
a1Row = sparse(1, i, R(i), 1, c);
% Sliced assignment
A1(i, :) = a1Row;
% Fix assignment into A2:
% pick random column
j = randi(c);
% Build a sparse row
a2Row = sparse(1, j, 1, 1, c);
% Sliced assignment
A2(i, :) = a2Row;
end
However, this form of assignment into a sparse matrix is probably not terribly efficient, so you might be better off using parfor to build up the sparse co-ordinates and values, and then performing the assignment afterwards, something like this:
% columns to assign
j = zeros(1,r);
% values to assign
v = zeros(1,r);
% Use parfor to build up j,v
parfor i = 1:r
j(i) = randi(c);
v(i) = 1;
end
% Build A2 directly from i,j,v
A2 = sparse(1:r, j, v, r, c);
  1 件のコメント
Luqman Saleem
Luqman Saleem 2019 年 9 月 17 日
Thank you very much

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeParallel Computing Fundamentals についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by