MATLAB Answers

0

Why does inputparser instantiated within a class subfunction not use the default for the first optional argument?

Hi there,
When I create an inputparser within a class method with a nested subfunction, it appears to not instantiate the first optional argument to the default value.
With the following test class:
classdef testclass < handle
properties
a
b
c
d
e
f
end
methods
function t = testclass(varargin)
p = inputParser;
addOptional(p,'a',1);
addOptional(p,'b',2);
addOptional(p,'c',3);
addOptional(p,'d',4);
addOptional(p,'e',5);
addOptional(p,'f',6);
parse(p,varargin{:});
t.a = p.Results.a;
t.b = p.Results.b;
t.c = p.Results.c;
t.d = p.Results.d;
t.e = p.Results.e;
t.f = p.Results.f;
end
function testfun(t,varargin)
testsubfun(t,varargin)
function testsubfun(t,varargin)
p = inputParser;
addOptional(p,'a',1);
addOptional(p,'b',2);
addOptional(p,'c',3);
addOptional(p,'d',4);
addOptional(p,'e',5);
addOptional(p,'f',6);
parse(p,varargin{:});
p.Results
end
end
end
end
If you call:
t=testclass('b',13,'c',14)
testfun(t,'b',13,'d',84)
I would expect the p.Results field to include the default value for the property 'a.' Instead, the entire varargin list is used as the value for that parameter. Is this a bug, or am I doing something wrong?
Thanks,
Lucas

  0 Comments

Sign in to comment.

1 Answer

Answer by Nagarjuna Manchineni on 15 May 2017
 Accepted Answer

You are properly using the 'inputParser' class. However, when you are passing the arguments using 'varargin' from 'testfun' to 'testsubfun', MATLAB treats the 'varargin' as a variable (a 1x1 cell array that contains 1x4 cells). So, you need to pass the 'varargin' parameters as it is to the 'testsubfun' by changing the 'testsubfun' call to the following syntax:
>> testsubfun(t,varargin{:})

  0 Comments

Sign in to comment.