- Define a template structure with default values.
- Use the ‘repmat’ function to replicate this template, forming an array of structures.
Help with Nested Structures Preallocation of data or how to clear Nested Structures inside of every loop.
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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;
0 comentarios
Respuestas (1)
Satwik
el 27 de Ag. de 2024
Hello,
You can efficiently preallocate your nested structure without relying on backward loops by using the following method:
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.
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!