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