parfor: slicing variable

1 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2020-12-9
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;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by