2017-02-14 137 views
0

我有一個至少有兩個必需的輸入參數的函數。根據第二個參數的值,可能會有第三個必需的輸入參數。我想知道什麼是使用MATLAB的輸入分析器來編寫一個包含這些需求的健壯功能的最佳方法?用MATLAB的輸入解析器解析互斥輸入參數

功能可能是這樣的:

function vout = test(ReqInpArg1, ReqInpArg2, varargin) 

ReqInpArg2可以包含以下字符串內容:

  • 'cash'
  • 'absHurdleRate'
  • 'none'

如果用戶選擇cash,那麼需要將另一個輸入參數numCashTicker定義爲varargin的一部分,例如, 'numCashTicker', 4。如果absHurdleRate已被選擇,則必須定義不同的輸入參數,例如, 'hurdleRate', 0.2。另一方面,如果已經選擇了none,則不必定義這些輸入參數。事實上,numCashTickerhurdleRate是相互排斥的,即它們不能同時被定義。另外,如果用戶沒有選擇none,他必須定義其他可變參數輸入參數之一。

什麼是實施這些要求的最佳實踐/最佳策略?

+0

能否請您發佈的代碼示例?也不要要求「最佳策略」,因爲它太籠統 - 使它更具體。 – Rotem

回答

0

我想出了以下解決方案:

function vout = test(timeSeries, hurdleRate, varargin)  
    p = inputParser; 
   expectedTypes = {'none', 'cash' 'absHurdleRate'};  
   default_numCashTicker = []; 
   default_absHurdleRate = []; 
   p.addRequired('timeSeries'); 
   p.addRequired('hurdleRate',@(x) any(validatestring(x,expectedTypes))); 
   p.addParameter('numCashTicker', default_numCashTicker); 
   p.addParameter('absHurdleRate', default_absHurdleRate); 
    
    parse(p, timeSeries, hurdleRate, varargin{:}); 

    numCashTicker = p.Results.numCashTicker; 

    switch hurdleRate 
     case 'none' 
      if ~isequal(numCashTicker, default_numCashTicker) 
       throw(MException('test:ParsingError', ... 
        '"none" does not require the "numCashTicker" parameter values"')); 
      elseif ~isequal(absHurdleRate, default_absHurdleRate) 
       throw(MException('test:ParsingError', ... 
        '"none" does not require the "absHurdleRate parameter values"')); 
      end 

     case 'cash' 
      if ~isnumeric(numCashTicker) 
       throw(MException('test:ParsingError', ... 
        '"cash" requires a numeric "numCashTicker" parameter value')); 
      elseif ~isequal(absHurdleRate, default_absHurdleRate) 
       throw(MException('CSmomRoC:ParsingError', ... 
        '"cash" does not require the "absHurdleRate parameter values"')); 
      end 

     case 'absHurdleRate' 
      if ~isnumeric(absHurdleRate) 
       throw(MException('CSmomRoC:ParsingError', ... 
        '"absHurdleRate" requires a numeric "absHurdleRate" parameter value')); 
      elseif ~isequal(numCashTicker, default_numCashTicker) 
       throw(MException('CSmomRoC:ParsingError', ... 
        '"absHurdleRate" does not require the "numCashTicker" parameter value.')); 
      end 
    end 

    ... 
    ... 
    ... 
end;