Clear Filters
Clear Filters

A parametric way of listing all elements of a struct array to be used for searching

1 view (last 30 days)
Hi experts
I have a fairly large struct variable with integers, strings, sub-structs - in other words a mess.
Is there a way to exhaustively seek through a full struct array with whatever subvariables and variable classes are present in the struct?
Now, I was hoping there would be a general way to search through any type of struct array, e.g. data{:}{:}{:}, so the that all branches have been exhaustively searched all the way to the bottom, like in a recursive parametric format approach?
Even if not, is there a way to 'string out' the tree, as to f.ex. set the nodes of all subarrays to link to the level 1 variable as to 'linearize' the structure while searching for a particular string or number?
Even if not, any ideas would be welcome..
Best
Claus
  1 Comment
Claus Andersson
Claus Andersson on 5 Jul 2021
Thanks 'Image Analyst'. I appreciate you taking time to answer! This is exactly what I needed, and it works, altough slow on my PC. I may have to consider establish SQL database down the road.
Again - many thanks!!

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 5 Jul 2021
Here is a start for you:
s.a = 1;
s.b.x=2;
s.b.y=3;
s.c = 4
fn = fieldnames(s) % Show in command window.
numFields = length(fn);
values = zeros(numFields, 1);
for k = 1 : length(fn)
thisField = fn{k};
if ~isstruct(s.(thisField))
values(k) = s.(thisField);
fprintf('The value of s.%s is %f.\n', thisField, values(k));
else
% The field is another structure
% TODO: Recurse into it by calling this function again.
fprintf('s.%s is another structure.\n', thisField);
end
end
You'll see:
s =
struct with fields:
a: 1
b: [1×1 struct]
c: 4
fn =
3×1 cell array
{'a'}
{'b'}
{'c'}
The value of s.a is 1.000000.
s.b is another structure.
The value of s.c is 4.000000.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!