How do I access structrure fields from input parser optional inputs

9 visualizzazioni (ultimi 30 giorni)
I am trying to pass in one and optionally two structures of the same type to a function using the input parser. I can access the fields of the first required structure, but I can't access the fields of the second optional structure. For the sample code below, a call of
ptest(s1)
works fine, but a call of,
ptest(s1, 's2', s2)
returns an error message of
Undefined variable "s2" or class "s2.dpri".
Error in ptest (line 22) fprintf('s2 field 1: %f\n', s2.dpri)
Here is the sample code:
function [] = ptest( s1, varargin )
%%Input Parser
p = inputParser;
p.StructExpand = false;
% Defaults for optional input
default_s2 = 'none';
addRequired(p,'s1', @(x) isstruct(x));
addParameter(p,'s2', default_s2, @(x) isstruct(x));
parse(p,s1,varargin{:});
% Check if optional parameters were specified
opt.s2 = ~any(strcmp('s2',p.UsingDefaults));
%%Actions based on s1
fprintf('s1 field 1: %f\n', s1.dpri)
fprintf('s1 field 2: %f\n', s1.dsec)
%%Actions based on s2
if opt.s2
fprintf('s2 field 1: %f\n', s2.dpri)
fprintf('s2 field 2: %f\n', s2.dsec)
end
end

Risposta accettata

Mohammad Abouali
Mohammad Abouali il 5 Apr 2015
Modificato: Mohammad Abouali il 5 Apr 2015
That's not how varargin works if you have
function ptest(s1,varargin)
....
end
then once you call it as:
ptest(s1,'s2',s2)
to access s2 within ptest you need to use varargin{2} for example you need to change the following part of your code as shown here
%%Actions based on s2
if opt.s2
%fprintf('s2 field 1: %f\n', s2.dpri)
%fprintf('s2 field 2: %f\n', s2.dsec)
fprintf('s2 field 1: %f\n', varargin{2}.dpri)
fprintf('s2 field 2: %f\n', varargin{2}.dsec)
end
alternatively you can access it using your parser object variable (p) as follow
p.Results.s2
This works if you have setup the parser object properly of course.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by