How to find variable strings within a structure?

12 views (last 30 days)
Adam R
Adam R on 4 Nov 2019
Answered: Deepak on 9 Jan 2025
Hi! I have a workspace variable named 'simulation' which houses 6 fields. These fields have a varying number of fields within them. Is it possible to search every 'branch' of this 'simulation' structure to find string values that contain '.m'?
For example, to find that:
simulation.system{1, 1}.system{1, 1}.system{1, 1}.initialization{1, 1}.name
contains the string 'drv_ctrl_look_ahead_init.m'

Answers (1)

Deepak
Deepak on 9 Jan 2025
We can search through a nested structure in MATLAB to find string values containing '.m' by implementing a recursive function that traverses each level of the structure. The function, "findMFilesInStruct", iterates over each field, checking if it is a structure, a cell array, or a string. If it encounters a structure, it recursively calls itself to delve deeper. For cell arrays, it iterates through each element, and for strings, it uses the "contains" function to check for '.m'. When a match is found, it prints the path to the console, allowing us to locate all instances of strings containing '.m' within the complex structure.
Below is the sample MATLAB code to achieve the same:
function findMFilesInStruct(structVar, parentPath)
% Loop over each field in the structure
fields = fieldnames(structVar);
for i = 1:length(fields)
fieldName = fields{i};
fieldValue = structVar.(fieldName);
% Construct the current path
currentPath = strcat(parentPath, '.', fieldName);
% Check if the field is a structure itself
if isstruct(fieldValue)
% Recursively search the sub-structure
findMFilesInStruct(fieldValue, currentPath);
elseif iscell(fieldValue)
% If the field is a cell array, iterate through its contents
for j = 1:numel(fieldValue)
if isstruct(fieldValue{j})
% Recursively search the sub-structure
findMFilesInStruct(fieldValue{j}, strcat(currentPath, '{', num2str(j), '}'));
elseif ischar(fieldValue{j}) && contains(fieldValue{j}, '.m')
% Check if the string contains '.m'
fprintf('Found .m file in: %s{%d}\n', currentPath, j);
end
end
elseif ischar(fieldValue) && contains(fieldValue, '.m')
% Check if the string contains '.m'
fprintf('Found .m file in: %s\n', currentPath);
end
end
end
findMFilesInStruct(simulation, 'simulation');
Please find attached the documentation of functions used for reference:
I hope this assists in resolving the issue.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!