storing value in 2D array in a parfor loop
26 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel Computing Fundamentals 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!