How do I access structrure fields from input parser optional inputs
显示 更早的评论
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
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!