File Exchange

image thumbnail

Set default values

version (1.32 KB) by Richie Cotton
A very simple function that initialises a missing or empty value in the caller function.


Updated 23 Mar 2010

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

In order to set default values for variables, I find the start of my functions littered with

if nargin < 1 || isempty(x)
x = 1;

if nargin < 2 || isempty(y)
y = 3;

This is pretty ugly, so I've created a wrapper to prettify it. Honestly, it's so simple that I nearly didn't upload this, but it does make your functions cleaner. Now the above is transformed to

SetDefaultValue(1, 'x', 1);
SetDefaultValue(2, 'y', 3);

Note that there are other ways to set defaults. See

Cite As

Richie Cotton (2021). Set default values (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (4)


Sorry, you still need to do the "evalin" trick
~evalin('caller', ['exist(''' argName ''', ''var'')']) || ...


@Marco, I ran into the same thing. I just modified the condition so that it tests for the variable's existence before trying to access it.

~exist(argName,'var') || ...

Added before the 'isempty(...' line

Marco Celesti

Thanks to the author for this useful function. I've used it with no problem with Matlab up to R2016a, with this release I get an error like this:

Error using evalin
Undefined function or variable 'a'.

Error in SetDefaultValue (line 19)
isempty(evalin('caller', argName))

Error in pippo (line 4)

when executing a dummy function "pippo":

function [ c ] = pippo( a, b )
%PIPPO Summary of this function goes here
% Detailed explanation goes here

c = a*b;


How should I fix it to get it working with R2016a (and possibly back compatible)?
Thanks a lot,


David Young

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!