Expand Struct Array Elements Rowwise
8 views (last 30 days)
Show older comments
Hi everyone,
is there a possibility in Matlab to epand a existing structy array rowwise ?
Example for one Field Element
for i=1:Steps:End
[Output.temp.Results]=fun(Input);
Output.Curve.Results.A(i,:)=Output.temp.Results.A
end
Now my Struct Array has about 50 Fieldelements. Is there an elegant way to do this in a few lines?
Thans for your help.
0 Comments
Answers (1)
Yukthi S
on 16 Feb 2024
Hi Jens Olschewski
I got that you wanted to expand the Struct array from one field element to 50 field elements. For that, you need to use a For loop in the function “fun” definition.
Since you did not provide any information about the rest of the code ,I am assuming some input values and also “fun” definition.
You can refer the following code which is verified in MATALB R2019a, to get a struct array with 50 field elements:
% Define Steps and End
Steps = 1;
End = 5;
% Initialize an empty struct for Output.Curve.Results
Output.Curve.Results = struct();
for i = 1:Steps:End
% Call the function and get the temporary results
Output.temp.Results = fun(i); % 'i' is passed as an input for the example
% Dynamically expand each field
fieldNames = fieldnames(Output.temp.Results);
for j = 1:numel(fieldNames)
fieldName = fieldNames{j};
% Check if the field already exists in Output.Curve.Results
if isfield(Output.Curve.Results, fieldName)
% Expand the field row-wise
Output.Curve.Results.(fieldName)(end+1,:) = Output.temp.Results.(fieldName);
else
% Initialize the field in Output.Curve.Results
Output.Curve.Results.(fieldName)(1,:) = Output.temp.Results.(fieldName);
end
end
end
% Display the structure of the final struct array
disp(fieldnames(Output.Curve.Results));
function result = fun(input)
% Initialize an empty struct
result = struct();
% Loop through to create 50 fields with random numbers
for k = 1:50
fieldName = sprintf("Field%d", k); % Generate field name dynamically
result.(fieldName) = rand(1, 1); % Assign a random number to the field
end
end
You can refer to the following MATLAB documentation to have more information on "fieldnames":https://in.mathworks.com/help/releases/R2019a/matlab/ref/fieldnames.html?searchHighlight=fieldnames&s_tid=doc_srchtitle
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!