Concatenate name fields in nested structure
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Ganesh
2024년 6월 13일
If you could upload the file 'database.mat' and describe what the output you would like to see is, it would be very helpful.
채택된 답변
Voss
2024년 6월 13일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!