inputparser mistakes option for value

조회 수: 3 (최근 30일)
Stefano Casarin
Stefano Casarin 2021년 1월 13일
답변: Prudhvi Peddagoni 2021년 1월 19일
Hello, I have created a method to draw some plots.
I have used inputParser to assign optional parameters (e.g. the y-axis label or the legend).
Here is the code:
function plot1signal(signal,titleName,varargin)
% Function to plot one signal per figure
% defaults
default_legendName = '';
default_yLabel = 'default';
p = inputParser;
validSignal = @(x) (isa(x,'timeseries') || isstruct(x));
addRequired(p,'signal',validSignal);
addRequired(p,'titleName',@ischar);
addOptional(p,'legendName',default_legendName,@ischar);
addOptional(p,'yLabel',default_yLabel,@ischar);
parse(p,signal,titleName,varargin{:});
...
end
As you can see there are 2 required inputs (a signal and the title), and two optional (y-label and the legend string).
I call this function with:
plot1signal(the_signal,'Title','yLabel','kN')
The expected behavior of the method would be having the default value for legendName and 'kN' for yLabel. Unfortunately inputParser seems to intepret 'yLabel' not only as an option but also as the input for 'legendName':
p.Results
ans =
struct with fields:
legendName: 'yLabel'
signal: [1×1 struct]
titleName: 'Title'
yLabel: 'kN'
Am I missing something?
  댓글 수: 1
Athrey Ranjith Krishnanunni
Athrey Ranjith Krishnanunni 2021년 1월 15일
addOptional adds optional positional arguments to your function, not Name-Value pairs. So, when you call your function as
plot1signal(the_signal,'Title','yLabel','kN')
inputParser takes the 1st and 2nd optional arguments as the values for legendName and yLabel, respectively (because they are positional, and you added legendName first to your function, followed by yLabel).
What you probably need is
addParameter(p,'legendName',default_legendName,@ischar);
addParameter(p,'yLabel',default_yLabel,@ischar);
instead.

댓글을 달려면 로그인하십시오.

채택된 답변

Prudhvi Peddagoni
Prudhvi Peddagoni 2021년 1월 19일
Hi,
Adding to what ARK has said, You can see the difference between functions like addRequired , addOptional and addParameter in this example.
Hope this helps.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Direction of Arrival Estimation에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by