Optional input parameters in function definition causes problems when function is used during another function

Dear all,
I have a function "density(d, r, k, dv, deltav)" where dv and deltav are optional inputs. To verify them i worked with:
if ~exist('dv','var')
do something
end
if exist('dv','var')
if ~exist('deltav','var')
do something else
end
end
in the definition of the function density. So I can call density(d,r,k) or density(d,r,k,dv) and it works. Now I have another function f2
function[a] = f2(other Inputs, d, r, dv, deltav)
...
for i = 1:n
k(i) = ...;
b = density(d, r, k(i), dv, deltav); %b is a Matrix %is in line 23 where the error occurs
a(i,:) = mean(b);
end
end
If I try now to call f2(other Inputs, d, r, dv) without deltav or even f2(other Inputs, d, r)
it gives me: Error using f2 (line 23) Not enough input arguments.
dv and deltav in f2 are only used in this specific line where density is called. So why do the "if exist" in density not work anymore? How can I solve this problem? Many thanks in advance

 Accepted Answer

So why do the "if exist" in density not work anymore?
They work just fine. It's f2() that is throwing the error message, not density().
The reason is that you didn't test for the existence of dv and deltav in f2's workspace as well. Since dv and deltav are referenced in line 23 of f2, f2 is trying to find them and cannot. The simplest solution is to use comma-separated-list expansion and varargin:
function [a] = f2(other Inputs, d, r, varargin)
...
for i = 1:n
k(i) = ...;
b = density(d, r, k(i), varargin{:}); %The {:} is important
a(i,:) = mean(b);
end
end

3 Comments

Many thanks! varargin does exactly what I wanted. In general: Is this the better way (i.e. varargin{1}=...) to test Inputs than with "exist"?
Not sure I follow the question. My use of varargin above avoids any testing of existence at all!
When you have to, the standard way to analyze the number of input arguments is with nargin, as Star Strider mentioned. I think exist(...,'var') is often a safer way, however, because if you later decide to change the number, order, or names of your inputs, exist(...,'var') commands will likely stay valid, whereas nargin processing will have to be reorganized.
ok, so i will keep the exist(...,'var') in my density function (there I Need to test) and use the varargin only in f2. Many thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on Functions in Help Center and File Exchange

Products

Asked:

on 2 Jan 2015

Commented:

on 2 Jan 2015

Community Treasure Hunt

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

Start Hunting!