フィルターのクリア

How do I access structrure fields from input parser optional inputs

13 ビュー (過去 30 日間)
Ron
Ron 2015 年 4 月 5 日
コメント済み: Ron 2015 年 4 月 6 日
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

採用された回答

Mohammad Abouali
Mohammad Abouali 2015 年 4 月 5 日
編集済み: Mohammad Abouali 2015 年 4 月 5 日
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.
  1 件のコメント
Ron
Ron 2015 年 4 月 6 日
Thank you. That is exactly what I needed.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by