Hi Martin Hock,
Please find an approach for prioritizing the inputs in the order arguments > config > default.
function math(numbers, options)
% Define the default options
defaultOptions = struct('basic', 'add');
% If a config file exists, read it and merge with default options
if exist('config.json')
configOptions = jsondecode(configFile);
optionsFromConfig = mergeOptions(defaultOptions, configOptions);
else
optionsFromConfig = defaultOptions;
end
% If options are provided manually, merge them with options from config
finalOptions = mergeOptions(optionsFromConfig, options);
% Do the math operation based on the final options
switch finalOptions.basic
case 'add'
% Call the add function with the provided numbers
result = add(numbers);
end
end
function mergedOptions = mergeOptions(defaults, overrides)
% Merge two structures, where fields in 'overrides' take precedence
mergedOptions = defaults;
overrideFields = fieldnames(overrides);
for i = 1:numel(overrideFields)
mergedOptions.(overrideFields{i}) = overrides.(overrideFields{i});
end
end
We create a variable “defaultOptions” to store the defaults. We check for the “config.json” file and if it exists we merge the options with the already created “defaultOptions”. In this situation, the “config.json” gets priority over “defaultOptions” and if any variable present in “config.json” is already present in “defaultOptions”, then it gets overridden.
Next, we create a variable, “finalOptions” that combines the options from config file, default options, and passed arguments.
The “mergeOptions” function takes two arguments; second one takes higher priority over the other. The variables are overridden with the second argument.
Hope this helps.
Thanks,
Ravi Chandra