storing value in 2D array in a parfor loop

26 views (last 30 days)
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?

Accepted Answer

Edric Ellis
Edric Ellis on 13 Sep 2019
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);

More Answers (0)

Categories

Find more on Parallel Computing Fundamentals 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!