How to assign values to arrays inside the PARFOR loop in Parallel Computing Toolbox?
24 views (last 30 days)
Show older comments
I tried to assign valued to a matrix at specified locations at each loop, but it did not work. It showed that the variable 'A' cannot be classified in parfor-loop. Maybe the problem came from the sliced variable 'b(:,i)'. But I do not know how to modify it.
A = rand(10, 10);
%b = (2:4);
b = zeros(3,4)
b(:,1) = [1 2 3];
b(:,2) = [2 3 4];
b(:,3) = [3 4 5];
b(:,4) = [4 5 6];
parfor i = 1:4
A(b(:,i), i) = ones(3, 1);
end
0 Comments
Accepted Answer
Edric Ellis
on 20 Sep 2023
To assign into A here, you need to follow the rules of sliced variables in parfor. In this case, you need to modify your code to assign to a whole row of column of A each time round the loop, like this:
A = rand(10, 10);
b = zeros(3,4)
b(:,1) = [1 2 3];
b(:,2) = [2 3 4];
b(:,3) = [3 4 5];
b(:,4) = [4 5 6];
parfor i = 1:4
tmpColumn = A(:, i);
tmpColumn(b(:,i)) = ones(3, 1);
A(:, i) = tmpColumn;
end
disp(A)
4 Comments
Edric Ellis
on 21 Sep 2023
In this case, you need to work a bit harder to make a vector fragment of the right (variable) size to append:
B0 = rand(12,12);
in = [0 9 13 29 38];
ind = cell(4,1);
ind{1} = [1 2 3];
ind{2} = [4 5];
ind{3} = [6 7 8 9];
ind{4} = [10 11 12];
A = zeros(0,1);
parfor i = 1:size(ind,1)
B = B0(ind{i},ind{i});
numToAppend = in(i+1) - in(i);
valsToAppend = zeros(numToAppend, 1);
valsToAppend(1:numel(B)) = B(:);
A = [A; valsToAppend];
end
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!