diff --git a/lib/+artoa/+data/getMember.m b/lib/+artoa/+data/getMember.m new file mode 100644 index 0000000000000000000000000000000000000000..fa984fd80618d7c1ae55ad67950210bbe5b6717a --- /dev/null +++ b/lib/+artoa/+data/getMember.m @@ -0,0 +1,32 @@ +function [memberValue] = getMember(pStructure, pMember, pDefaultValue) +%GETMEMBER Returns the given member in the structure if existent, the given default value otherwise. +% Checks for the existence of the member by using artoa.data.hasMember. +% If the value exists, it will be returned. Otherwise it will return the +% default value. +% +% Parameters: +% pStructure (struct) The structure where the member is stored in. +% pMember (cell) A 1D cell of chars, each entry representing the +% level of the structure. +% pDefaultValue (mixed) The default value that is returned if the +% member does not exist. + +%% Initialization +if ~exist(pDefaultValue, 'var') + pDefaultValue = ''; +end + +memberValue = pDefaultValue; + +%% Return member if it exists +if ~artoa.data.hasMember(pStructure, pMember) + return; +end + +memberValue = pStructure; +for i = 1:length(pMember) + memberValue = memberValue.(pMember{i}); +end + +end + diff --git a/lib/+artoa/+data/hasMember.m b/lib/+artoa/+data/hasMember.m new file mode 100644 index 0000000000000000000000000000000000000000..0acc528ef0cb4bab99c413b0474bd0fd640c41d1 --- /dev/null +++ b/lib/+artoa/+data/hasMember.m @@ -0,0 +1,40 @@ +function [boolean] = hasMember(pStructure, varargin) +%HASVARIABLE Checks the given structure if the member is available. +% Checks if the fields are available in the given structure. +% Example: +% hasMember(S, 'hello', 'world') +% checks if S.hello.world member is available. +% Parameters: +% pStructure (struct) The structure where the member will be +% searched for. +% varargin (char) Every additional char array represents the +% level of the structure. +% +% Returns (bool) False if the member is not available. + +%% Initialization +boolean = false; + +%% Parameter check +if isempty(varargin) + return; +end + +if length(varargin) == 1 && iscell(varargin{1}) + varargin = varargin{1}; +end + +%% Check all levels +currentLevel = pStructure; +for i = 1:length(varargin) + if isfield(currentLevel, varargin{i}) + currentLevel = currentLevel.(varargin{i}); + else + return; + end +end + +boolean = true; + +end +