diff copyWithDefault.m @ 425:e56dbd9e4196 feature/grids

Merge feature/beams
author Jonatan Werpers <jonatan@werpers.com>
date Tue, 07 Feb 2017 16:09:02 +0100
parents 499653b553b8
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/copyWithDefault.m	Tue Feb 07 16:09:02 2017 +0100
@@ -0,0 +1,31 @@
+% Copy the struct src to dest with default values from default
+%   dest = copyWithDefault(src, default)
+function dest = copyWithDefault(src, default)
+    % src does not have a value => use default
+    if isempty(src)
+        dest = default;
+        return
+    end
+
+    % src has a value and is not a struct => use src
+    % src has a value and default is not a struct => use src
+    if ~isstruct(src) || ~isstruct(default)
+        dest = src;
+        return
+    end
+
+
+    % src has a value and is a struct => add all default fields
+    dest = src;
+
+    fn = fieldnames(default);
+    for i = 1:length(fn)
+        if isfield(src, fn{i})
+            srcField = src.(fn{i});
+        else
+            srcField = [];
+        end
+
+        dest.(fn{i}) = copyWithDefault(srcField, default.(fn{i}));
+    end
+end