MATLAB Answers

0

storing value in 2D array in a parfor loop

Asked by Luqman Saleem on 12 Sep 2019
Latest activity Commented on by Luqman Saleem on 17 Sep 2019
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?

  0 Comments

Sign in to comment.

1 Answer

Answer by Edric Ellis
on 13 Sep 2019
 Accepted Answer

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 Comment

Thank you very much

Sign in to comment.