Set default values of input variables

A quick function for setting the default value of some variables
34 Downloads
Updated 25 Oct 2016

View License

default is useful for setting the default value of an optional value.
For example,
a function
function c=add(a,b)
default('a',1);
default('b',2);
c=a+b;
gives the following results:
>> add()
ans =

3

>> add(2)

ans =

4

>> add(2,5)

ans =

7

default can assign ordinary variables, or it can assign fields of structs.

default counts empty variables as unset, and so will assign them a default value, unless the opposite behavior is specified with count_empty=0.

For example,
>> add([],4)

ans =

5

allows us to default the first input while specifying the second.

default works by executing 'isempty' and 'exist' in the caller workspace using the 'evalin' command. It uses 'assignin' to assign the value.

Cite As

Joe Eichholz (2024). Set default values of input variables (https://www.mathworks.com/matlabcentral/fileexchange/59853-set-default-values-of-input-variables), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Variables in Help Center and MATLAB Answers
Tags Add Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.1.0.0

Added ability to deal with setting fields.

1.0.0.0

Just added a more descriptive title

Added a couple more use cases.