Parfor sliced variable with nonuniform sized slices

1 回表示 (過去 30 日間)
Andy Hsu
Andy Hsu 2022 年 4 月 5 日
回答済み: Vatsal 2023 年 11 月 17 日
Hi all,
I am having some trouble with implementing a parfor loop into my code -- my challenge can be summed up with the following code:
matrix = zeros(20, 2);
firstIndex = [1 4 10 19];
maximumLength = [3 6 9 2];
parfor i = 1:length(maximumLength)
randLength = randi(maximumLength(i));
firstIndex_ = firstIndex(i);
matrix(firstIndex_:firstIndex_+randLength-1,:) = zeros(randLength,2);
end
MATLAB informs me that due to the way that matrix is indexed, this is an invalid parfor loop. I understand that the issue boils down to the fact that the "slices" of matrix are of nonuniform sizes and can be easily solved using a cell array. However, is there a way to resolve this issue without using a cell array and keeping matrix as, well, a matrix?

回答 (1 件)

Vatsal
Vatsal 2023 年 11 月 17 日
Hi,
I understand that you are facing a problem due to the non-uniform slicing of the matrix in the parfor loop. There is no straightforward way to resolve this issue while keeping the matrix as a matrix. You can create a temporary matrix, perform the operations, and then assign the results back to the main matrix after the loop.
I am also attaching the modified code below: -
matrix = zeros(20, 2);
firstIndex = [1 4 10 19];
maximumLength = [3 6 9 2];
tempMatrix = cell(1, length(maximumLength));
parfor i = 1:length(maximumLength)
randLength = randi(maximumLength(i));
firstIndex_ = firstIndex(i);
tempMatrix{i} = zeros(randLength,2);
end
for i = 1:length(maximumLength)
firstIndex_ = firstIndex(i);
matrix(firstIndex_:firstIndex_+size(tempMatrix{i},1)-1,:) = tempMatrix{i};
end
I hope this helps!

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by