Help with Nested Structures Preallocation of data or how to clear Nested Structures inside of every loop.

2 ビュー (過去 30 日間)
I need to prelocate data in this type of Nested Structures. I didn't find any easy way exept for doing it in backwards for loops. Is there a better way?
ControlResults_con(ControlCycleNumber_con).Quality = rms(y_con(k-LengthOfControlCycle+1:k));
ControlResults_con(ControlCycleNumber_con).Parameters.P = P_control_con;
ControlResults_con(ControlCycleNumber_con).Parameters.D = D_control_con;
ControlResults_con(ControlCycleNumber_con).Parameters.I = I_control_con;

回答 (1 件)

Satwik
Satwik 2024 年 8 月 27 日
Hello,
You can efficiently preallocate your nested structure without relying on backward loops by using the following method:
  1. Define a template structure with default values.
  2. Use the ‘repmat’ function to replicate this template, forming an array of structures.
Here is an example of how you can implement this:
% Define the number of control cycles
numControlCycles = 100; % Example number
% Define a template structure with default values
template.Quality = NaN; % or 0, or any default value you prefer
template.Parameters.P = NaN;
template.Parameters.D = NaN;
template.Parameters.I = NaN;
% Preallocate the structure array
ControlResults_con = repmat(template, numControlCycles, 1);
% Now you can fill in the values in a loop
for ControlCycleNumber_con = 1:numControlCycles
% Example calculations or assignments
ControlResults_con(ControlCycleNumber_con).Quality = rms(y_con(k-LengthOfControlCycle+1:k));
ControlResults_con(ControlCycleNumber_con).Parameters.P = P_control_con;
ControlResults_con(ControlCycleNumber_con).Parameters.D = D_control_con;
ControlResults_con(ControlCycleNumber_con).Parameters.I = I_control_con;
end
For more information on the ‘repmat’ function you can refer to this documentation:
This method is more efficient than dynamically expanding the structure array within a loop, as it prevents repeated memory allocation.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by