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

採用された回答

Edric Ellis
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 = 3×4
0 0 0 0 0 0 0 0 0 0 0 0
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
Starting parallel pool (parpool) using the 'Processes' profile ... Parallel pool using the 'Processes' profile is shutting down.
disp(A)
1.0000 0.9683 0.1756 0.8298 0.3531 0.3313 0.3907 0.9286 0.0291 0.0008 1.0000 1.0000 0.3131 0.2572 0.3250 0.9650 0.7758 0.3500 0.0066 0.4571 1.0000 1.0000 1.0000 0.3183 0.4465 0.7105 0.6725 0.6469 0.6300 0.8838 0.8736 1.0000 1.0000 1.0000 0.8056 0.5376 0.0758 0.4828 0.6726 0.4277 0.7046 0.2091 1.0000 1.0000 0.4532 0.8524 0.7978 0.7761 0.6336 0.8924 0.7084 0.9754 0.0910 1.0000 0.3777 0.5662 0.7766 0.8363 0.1298 0.4706 0.8724 0.1200 0.6708 0.3640 0.6861 0.1135 0.0157 0.7365 0.7295 0.9218 0.9134 0.2101 0.6980 0.4086 0.1757 0.7772 0.1264 0.9909 0.0295 0.4074 0.2208 0.4582 0.4297 0.0378 0.1022 0.1332 0.5524 0.5354 0.8923 0.1826 0.9337 0.4130 0.9842 0.6144 0.4617 0.9431 0.6865 0.5676 0.2264 0.4760
  4 件のコメント
Yanda CHEN
Yanda CHEN 2023 年 9 月 21 日
Thank you so much for your reply. What if the values of B changes in each loop, so that A can not be recognized as a matrix:
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(38,1);
parfor i = 1:size(ind,1)
B = B0(ind{i},ind{i});
A(in(i)+1:in(i+1)) = B(:);
end
Looking forward to your replay.
Edric Ellis
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 ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by