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

2 views (last 30 days)
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;

Answers (1)

Satwik
Satwik on 27 Aug 2024
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.

Categories

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

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!