fieldnames.m 1.06 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function fieldNames = fieldnames(myStruct)
% misc.fieldnames returns all field names of myStruct. If myStruct is a nested struct, i.e. a struct
% containing structs as fields, fields will return a string array containing all branches separating
% every layer with a dot, for instance (level1).(level2).(level3)...
%%
% Example
%		misc.fieldnames(misc.setfield(struct("blub", 1337), "topLevel.lowerLevel.data", 42));

arguments
	myStruct struct;
end

fieldNames = string([]);
for thisFieldName = string(fieldnames(myStruct)).'
	fieldNames = [fieldNames; fieldNamesOfBranch(myStruct, thisFieldName)];
end % for thisFieldName
	

end % fieldnames()

function result = fieldNamesOfBranch(myStruct, branchName)
arguments
	myStruct struct;
	branchName (1, 1) string;
end % arguments

tmpField = misc.getfield(myStruct, branchName);
if isstruct(tmpField)
	subBranchNames = branchName + "." + string(fieldnames(tmpField));
	result = string([]);
	for it = 1 : numel(subBranchNames)
		result = [result; fieldNamesOfBranch(myStruct, subBranchNames(it))];
	end
else
	result = branchName;
end
end %