Parfor sliced variable with nonuniform sized slices
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
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!
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!