Parfor sliced variable with nonuniform sized slices

1 visualizzazione (ultimi 30 giorni)
Andy Hsu il 5 Apr 2022
Risposto: Vatsal il 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?
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposte (1)

Vatsal il 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!
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by