parfor: slicing variable

3 views (last 30 days)
Dan H
Dan H on 9 Dec 2020
Answered: Walter Roberson on 9 Dec 2020
Hello,
I ask for assistance with slicing a variable for use with "parfor".
The challenge is, I don't want to / don't need to iterate over the whole array, but I need to change the values of some segments of the array.
The segment size to be changed is determined before the loop (variable "indices" and "step").
So the loop variable ("ii") is not identical to the array index.
Best regards,
Dan
clear all;
a = rand(20,1); % vector to be modified
b = a;
indices = [2, 5, 9, 14]; %arbitrary start indices, for which the following n values should be changed
step = [1, 2, 2, 4]; % number of values to be changed
%% the for loop works
for ii = 1 : length(indices)
start_index = indices(ii);
end_index = start_index + step(ii);
a(indices(ii) : indices(ii)+step(ii)-1) = nan(step(ii), 1);
end
%% parfor does not work
parfor ii = 1 : length(indices)
start_index = indices(ii);
end_index = start_index + step(ii);
b(start_index : end_index) = nan(step(ii), 1);
end

Accepted Answer

Walter Roberson
Walter Roberson on 9 Dec 2020
This is not something you can do with parfor. parfor can only be used where the indices written to are a very simple computation from the indices.
I suggest you consider using sub2ind() to build up lists of linear indices to change, and then do a simple non-parallel b(list_of_indices) = nan .
If necessary (very long list) you could compute the indices in a parfor, returning them as data inside cell locations, like
parfor ii = 1 : length(indices)
start_index = indices(ii);
end_index = start_index + step(ii);
bidx{ii} = start_index : end_index - 1;
end
b(horzcat(bidx{:})) = nan;

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!