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 CenterFile Exchange 中查找有关 Loops 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