Parfor sliced variable with nonuniform sized slices

조회 수: 2 (최근 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 CenterFile Exchange에서 Loops 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