How to find variable strings within a structure?

12 ビュー (過去 30 日間)
Adam R
Adam R 2019 年 11 月 4 日
回答済み: Deepak 2025 年 1 月 9 日
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'

回答 (1 件)

Deepak
Deepak 2025 年 1 月 9 日
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.

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by