Effacer les filtres
Effacer les filtres

How do I access structrure fields from input parser optional inputs

13 vues (au cours des 30 derniers jours)
Ron
Ron le 5 Avr 2015
Commenté : Ron le 6 Avr 2015
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

Réponse acceptée

Mohammad Abouali
Mohammad Abouali le 5 Avr 2015
Modifié(e) : Mohammad Abouali le 5 Avr 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.

Plus de réponses (0)

Catégories

En savoir plus sur Workspace Variables and MAT-Files dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by