Concatenate name fields in nested structure
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello,
I am trying to save value of the data placed in the last fields in nested structure by concatenating string in recursion. The name of the file should string composed of the all preceding fields in structure.
However I am not able to save previous fields.
The code is as follows:
nameDataBase = 'database.mat';
structNest = load([pathFolder, nameDataBase]);
structFields = myIsField(structNest, 'data');
pathOutputFile = pathFolder;
fileName = ''
function isFieldResult = myIsField (inStruct, fieldName)
% inStruct is the name of the structure or an array of structures to search
% fieldName is the name of the field for which the function searches
B = struct();
display('output folder')
isFieldResult = 0;
f = fieldnames(inStruct(1))
f1 = string(fieldnames(inStruct(1)))
for i=1:1%length(f)
display("i")
i
if(strcmp(f{i},strtrim(fieldName)))
isFieldResult = 1;
display('data found - end')
B.(f{i}) = inStruct(1).(f{i})
data = getfield(B,'data')
return;
elseif isstruct(inStruct(1).(f{i}))
isFieldResult = myIsField(inStruct(1).(f{i}), fieldName);
B.(f{i}) = inStruct(1).(f{i})
if isFieldResult
display('time found -loop')
return;
end
end
end
1 Kommentar
Ganesh
am 13 Jun. 2024
If you could upload the file 'database.mat' and describe what the output you would like to see is, it would be very helpful.
Akzeptierte Antwort
Voss
am 13 Jun. 2024
S = struct( ...
'A1',1, ...
'A2',struct('B1',2,'not_data',3,'data',4), ...
'A3',struct( ...
'B1',struct('not_data',5), ...
'B2',struct( ...
'C1',struct('data',6), ...
'data',struct( ...
'D1',struct('data',7)))))
S.A2
S.A3
S.A3.B1
S.A3.B2
S.A3.B2.C1
S.A3.B2.data
S.A3.B2.data.D1
function [out,data] = get_full_field_names(S,name,str)
out = strings(0);
data = cell(0);
if nargin < 3
str = "";
end
f = fieldnames(S);
for ii = 1:numel(f)
if isstruct(S.(f{ii}))
[new_out,new_data] = get_full_field_names(S.(f{ii}),name,str+f{ii}+".");
out = [out, new_out];
data = [data, new_data];
elseif strcmp(f{ii},name)
out = [out, str+name];
data = [data, {S.(f{ii})}];
end
end
end
[names,data] = get_full_field_names(S,'data')
[names,data] = get_full_field_names(S,'not_data')
[names,data] = get_full_field_names(S,'something_else')
5 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!