How to use parfor to create an array of SimulationInput objects?
1 回表示 (過去 30 日間)
古いコメントを表示
I have a piece of code used to generate an array of SimulationInput objects, it works in a normal for loop, but when I switch to parfor loop, it throws error. The code named `generate_simin` is like the following:
model_name = 'my_model';
params_list = linspace(0,1,100);
numSims = length(params_list);
inCmd(1:numSims) = Simulink.SimulationInput(model_name); % initialize an array of simulationInput objects
parfor idx = 1:numSims % replaced for with parfor for performance
inCmd(idx) = setVariable(inCmd(idx),'parameter_1',params_list(idx));
end
Then I received error:
Error generate_simin/parfor%supply_1
Index exceeds the number of array elements (0).
Error in generate_parsim>generate_simin (line 5)
parfor idx = 1:numSims % replaced for with parfor for performance
I followed the principle that each parfor iteration should be independent and in non-deterministic order, and that is why I initialized an array as a place holder to store the results for each iteration. The error seems to say that my pre-initialized array of SimulationInput objects 'inCmd' has 0 elements. But this is not true because if I type 'size(inCmd)' in my MATLAB command window, I will get:
size(inCmd)
ans =
1 100
Clearly, it is an array with 100 elements. So why is parfor throwing error saying:
Index exceeds the number of array elements (0).
Any help or hint is appreciated!
Edit: I found out by myself that the problem was actually not with the syntax of SimulationInput, but stems from my illegal use of parfor loop. In my parfor loop, I had some if conditions. And in those if conditions, different variables were called, some exists in one type of upstream data, some exists in another type of upstream data. Something like this:
parfor idx = 1:numSims
if data_type == 1
params_list = type_1_specific_params_list;
end
if data_type == 2
params_list = type_2_specific_params_list;
end
inCmd(idx) = setVariable(inCmd(idx),'parameter_1',params_list(idx));
end
But each time I run this parfor loop, only one of the two variables type_1_specific_params_list or type_1_specific_params_list were defined. And this was actually why I had the error:
Index exceeds the number of array elements (0).
2 件のコメント
Edric Ellis
2022 年 3 月 21 日
Which version of MATLAB are you using? I tried your reproduction steps in R2022a, and they appeared to work correctly.
採用された回答
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Parallel for-Loops (parfor) についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!