Parfor sliced variable with nonuniform sized slices

2 vues (au cours des 30 derniers jours)
Andy Hsu
Andy Hsu le 5 Avr 2022
Réponse apportée : Vatsal le 17 Nov 2023
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?

Réponses (1)

Vatsal
Vatsal le 17 Nov 2023
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!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by