How to assign values to arrays inside the PARFOR loop in Parallel Computing Toolbox?
24 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Edric Ellis
2023-9-20
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 个评论
Edric Ellis
2023-9-21
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!