View License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Set default values

Join the 15-year community celebration.

Play games and win prizes!

» Learn more

5.0
5.0 | 3 ratings Rate this file 2 Downloads (last 30 days) File Size: 1.32 KB File ID: #27056 Version: 1.0

Set default values

by

Richie Cotton (view profile)

 

A very simple function that initialises a missing or empty value in the caller function.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

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

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

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

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
http://blogs.mathworks.com/loren/2009/05/05/nice-way-to-set-function-defaults/

MATLAB release MATLAB 7.9 (R2009b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (4)
20 May 2016 Terry

Terry (view profile)

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

Comment only
20 May 2016 Terry

Terry (view profile)

@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

01 Apr 2016 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)
SetDefaultValue(1,'a',1)

when executing a dummy function "pippo":

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

c = a*b;

end

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

Marco

23 Mar 2010 David Young

David Young (view profile)

 

Contact us