Nested parfor and for-Loops gives error

1 view (last 30 days)
Hi,
My code is as follows:
result1 = nan(totaal, 7);
tx_range=tx_min:stepsize_t:tx_max;
totaal_temp=1e6;
parfor t_x_index = 1:numel(tx_range)
result1_temp = zeros(totaal_temp, 7);
t_x = tx_range(t_x_index);
disp(['t_x = ', num2str(t_x)]);
% multiple for loops which does not interact with "t_x_index" or "t_x". So, this part is basically independent of the parfor variable.
% the results of the for loops are saved into a variable named "result1_temp".
% now, i want to store the "result1_temp" in "result1":
indexing = (1:size(result1_temp, 1)) + (t_x_index - 1) * size(result1_temp, 1);
result1(indexing, :) = result1_temp;
end
Matlab gives me an error and does not allow me to run this. The error says:
Matlab PARFOR loop cannot run due to the way variable "result1" is used. Could someone help with what could be wrong here?
Thanks.

Accepted Answer

Shivam
Shivam on 9 Oct 2023
Edited: Shivam on 9 Oct 2023
Hi Moein,
I understand that you are facing an error while indexing into "result1" inside PARFOR loop.
To address this, you can store the results in a temporary variable inside the PARFOR loop and then assign them to the appropriate section of "result1" outside the PARFOR loop.
You can refer the following workaround to work on changes:
% ...
parfor t_x_index = 1:numel(tx_range)
% ...
% ...
% Store the "result1_temp" in the temporary variable "result1_temp_combined"
result1_temp_combined{t_x_index} = result1_temp;
end
% Assign the results from "result1_temp_combined" to the appropriate section of "result1"
for t_x_index = 1:numel(tx_range)
indexing = (1:size(result1_temp_combined{t_x_index}, 1)) + (t_x_index - 1) * size(result1_temp_combined{t_x_index}, 1);
result1(indexing, :) = result1_temp_combined{t_x_index};
end
I hope it helps.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!