71

名前と値のペアとしてオプションの引数を取る関数があります。

function example(varargin)
% Lots of set up stuff
vargs = varargin;
nargs = length(vargs);
names = vargs(1:2:nargs);
values = vargs(2:2:nargs);

validnames = {'foo', 'bar', 'baz'};    
for name = names
   validatestring(name{:}, validnames);
end

% Do something ...
foo = strmatch('foo', names);
disp(values(foo))
end

example('foo', 1:10, 'bar', 'qwerty')

適切な値を抽出するのに多くの労力が必要なようです(そして、それでも、不適切に指定された入力に対しては、特に堅牢ではありません)。これらの名前/値のペアを処理するためのより良い方法はありますか?支援するMATLABに付属しているヘルパー関数はありますか?

4

15 に答える 15

66

オプションに構造を使用することを好みます。これにより、オプションを保存する簡単な方法と、オプションを定義する簡単な方法が提供されます。また、全体がかなりコンパクトになります。

function example(varargin)

%# define defaults at the beginning of the code so that you do not need to
%# scroll way down in case you want to change something or if the help is
%# incomplete
options = struct('firstparameter',1,'secondparameter',magic(3));

%# read the acceptable names
optionNames = fieldnames(options);

%# count arguments
nArgs = length(varargin);
if round(nArgs/2)~=nArgs/2
   error('EXAMPLE needs propertyName/propertyValue pairs')
end

for pair = reshape(varargin,2,[]) %# pair is {propName;propValue}
   inpName = lower(pair{1}); %# make case insensitive

   if any(strcmp(inpName,optionNames))
      %# overwrite options. If you want you can test for the right class here
      %# Also, if you find out that there is an option you keep getting wrong,
      %# you can use "if strcmp(inpName,'problemOption'),testMore,end"-statements
      options.(inpName) = pair{2};
   else
      error('%s is not a recognized parameter name',inpName)
   end
end
于 2010-05-05T19:40:45.583 に答える
45

InputParserはこれを支援します。詳細については、関数入力の解析を参照してください。

于 2010-05-05T17:47:24.487 に答える
13

私はこれについて何時間もヤクすることができましたが、それでも一般的なMatlab署名処理の良いゲシュタルトビューを持っていません。しかし、ここにいくつかのアドバイスがあります。

まず、入力タイプを検証するために自由放任主義のアプローチを取ります。発信者を信頼します。強い型のテストが本当に必要な場合は、Javaのような静的言語が必要です。Matlabのあらゆる場所で型の安全性を強化してみてください。そうすれば、LOCと実行時間のかなりの部分が、Matlabの多くのパワーと開発速度と引き換えにユーザーランドでの時間型テストと強制の実行に費やされることになります。 。私はこれを難しい方法で学びました。

APIシグニチャ(コマンドラインからではなく、他の関数から呼び出すことを目的とした関数)の場合、vararginの代わりに単一のArgs引数を使用することを検討してください。次に、varargin署名のコンマ区切りリストとの間で変換しなくても、複数の引数間で受け渡すことができます。Jonasが言うように、構造体は非常に便利です。構造体とn行2列の{name、value; ...}セルの間にも優れた同型性があり、関数内でそれらを変換して内部で使用したいものに変換する関数をいくつか設定できます。

function example(args)
%EXAMPLE
%
% Where args is a struct or {name,val;...} cell array

inputParserを使用する場合でも、これらの他の優れた例のように独自のname / valパーサーをロールする場合でも、name/valシグネチャを持つ関数の先頭から呼び出す別の標準関数にパッケージ化します。書き出すのに便利なデータ構造のデフォルト値リストを受け入れるようにすると、arg-parsing呼び出しは関数の署名宣言のようになり、読みやすくなり、ボイラープレートコードのコピーアンドペーストを回避できます。

解析呼び出しは次のようになります。

function out = my_example_function(varargin)
%MY_EXAMPLE_FUNCTION Example function 

% No type handling
args = parsemyargs(varargin, {
    'Stations'  {'ORD','SFO','LGA'}
    'Reading'   'Min Temp'
    'FromDate'  '1/1/2000'
    'ToDate'    today
    'Units'     'deg. C'
    });
fprintf('\nArgs:\n');
disp(args);

% With type handling
typed_args = parsemyargs(varargin, {
    'Stations'  {'ORD','SFO','LGA'}     'cellstr'
    'Reading'   'Min Temp'              []
    'FromDate'  '1/1/2000'              'datenum'
    'ToDate'    today                   'datenum'
    'Units'     'deg. C'                []
    });
fprintf('\nWith type handling:\n');
disp(typed_args);

% And now in your function body, you just reference stuff like
% args.Stations
% args.FromDate

そして、これが名前/値の解析をそのように実装する関数です。それをくり抜いて、inputParser、独自の型規則などに置き換えることができます。n行2列のセル規則は、読みやすいソースコードになると思います。それを維持することを検討してください。構造体は通常、受信コードで処理する方が便利ですが、n行2列のセルは式とリテラルを使用して作成する方が便利です。(構造体には、各行で「、...」の継続が必要であり、セル値が非スカラー構造体に拡張されないように保護する必要があります。)

function out = parsemyargs(args, defaults)
%PARSEMYARGS Arg parser helper
%
% out = parsemyargs(Args, Defaults)
%
% Parses name/value argument pairs.
%
% Args is what you pass your varargin in to. It may be
%
% ArgTypes is a list of argument names, default values, and optionally
% argument types for the inputs. It is an n-by-1, n-by-2 or n-by-3 cell in one
% of these forms forms:
%   { Name; ... }
%   { Name, DefaultValue; ... }
%   { Name, DefaultValue, Type; ... }
% You may also pass a struct, which is converted to the first form, or a
% cell row vector containing name/value pairs as 
%   { Name,DefaultValue, Name,DefaultValue,... }
% Row vectors are only supported because it's unambiguous when the 2-d form
% has at most 3 columns. If there were more columns possible, I think you'd
% have to require the 2-d form because 4-element long vectors would be
% ambiguous as to whether they were on record, or two records with two
% columns omitted.
%
% Returns struct.
%
% This is slow - don't use name/value signatures functions that will called
% in tight loops.

args = structify(args);
defaults = parse_defaults(defaults);

% You could normalize case if you want to. I recommend you don't; it's a runtime cost
% and just one more potential source of inconsistency.
%[args,defaults] = normalize_case_somehow(args, defaults);

out = merge_args(args, defaults);

%%
function out = parse_defaults(x)
%PARSE_DEFAULTS Parse the default arg spec structure
%
% Returns n-by-3 cellrec in form {Name,DefaultValue,Type;...}.

if isstruct(x)
    if ~isscalar(x)
        error('struct defaults must be scalar');
    end
    x = [fieldnames(s) struct2cell(s)];
end
if ~iscell(x)
    error('invalid defaults');
end

% Allow {name,val, name,val,...} row vectors
% Does not work for the general case of >3 columns in the 2-d form!
if size(x,1) == 1 && size(x,2) > 3
    x = reshape(x, [numel(x)/2 2]);
end

% Fill in omitted columns
if size(x,2) < 2
    x(:,2) = {[]}; % Make everything default to value []
end
if size(x,2) < 3
    x(:,3) = {[]}; % No default type conversion
end

out = x;

%%
function out = structify(x)
%STRUCTIFY Convert a struct or name/value list or record list to struct

if isempty(x)
    out = struct;
elseif iscell(x)
    % Cells can be {name,val;...} or {name,val,...}
    if (size(x,1) == 1) && size(x,2) > 2
        % Reshape {name,val, name,val, ... } list to {name,val; ... }
        x = reshape(x, [2 numel(x)/2]);
    end
    if size(x,2) ~= 2
        error('Invalid args: cells must be n-by-2 {name,val;...} or vector {name,val,...} list');
    end

    % Convert {name,val, name,val, ...} list to struct
    if ~iscellstr(x(:,1))
        error('Invalid names in name/val argument list');
    end
    % Little trick for building structs from name/vals
    % This protects cellstr arguments from expanding into nonscalar structs
    x(:,2) = num2cell(x(:,2)); 
    x = x';
    x = x(:);
    out = struct(x{:});
elseif isstruct(x)
    if ~isscalar(x)
        error('struct args must be scalar');
    end
    out = x;
end

%%
function out = merge_args(args, defaults)

out = structify(defaults(:,[1 2]));
% Apply user arguments
% You could normalize case if you wanted, but I avoid it because it's a
% runtime cost and one more chance for inconsistency.
names = fieldnames(args);
for i = 1:numel(names)
    out.(names{i}) = args.(names{i});
end
% Check and convert types
for i = 1:size(defaults,1)
    [name,defaultVal,type] = defaults{i,:};
    if ~isempty(type)
        out.(name) = needa(type, out.(name), type);
    end
end

%%
function out = needa(type, value, name)
%NEEDA Check that a value is of a given type, and convert if needed
%
% out = needa(type, value)

% HACK to support common 'pseudotypes' that aren't real Matlab types
switch type
    case 'cellstr'
        isThatType = iscellstr(value);
    case 'datenum'
        isThatType = isnumeric(value);
    otherwise
        isThatType = isa(value, type);
end

if isThatType
    out = value;
else
    % Here you can auto-convert if you're feeling brave. Assumes that the
    % conversion constructor form of all type names works.
    % Unfortunately this ends up with bad results if you try converting
    % between string and number (you get Unicode encoding/decoding). Use
    % at your discretion.
    % If you don't want to try autoconverting, just throw an error instead,
    % with:
    % error('Argument %s must be a %s; got a %s', name, type, class(value));
    try
        out = feval(type, value);
    catch err
        error('Failed converting argument %s from %s to %s: %s',...
            name, class(value), type, err.message);
    end
end

文字列とdatenumがMatlabのファーストクラスの型ではないのは非常に残念です。

于 2010-05-05T21:44:19.677 に答える
13

MathWorksはこの殴打された馬を復活させましたが、このニーズに直接答える非常に便利な機能を備えています。これは関数の引数の検証(ドキュメントで検索できるフレーズ)と呼ばれ、リリースR2019b+に付属しています。MathWorksもそれについてのビデオを作成しました。検証は、人々が何年にもわたって思いついた「トリック」とほとんど同じように機能します。次に例を示します。

function ret = example( inputDir, proj, options )
%EXAMPLE An example.
% Do it like this.
% See THEOTHEREXAMPLE.

    arguments
        inputDir (1, :) char
        proj (1, 1) projector
        options.foo char {mustBeMember(options.foo, {'bar' 'baz'})} = 'bar'
        options.Angle (1, 1) {double, integer} = 45
        options.Plot (1, 1) logical = false
    end

    % Code always follows 'arguments' block.
    ret = [];
    switch options.foo
        case 'bar'
            ret = sind(options.Angle);
        case 'baz'
            ret = cosd(options.Angle);
    end

    if options.Plot
        plot(proj.x, proj.y)
    end

end

開梱は次のとおりです。

ブロックはコードのarguments前に来る必要があり(ヘルプブロックの後にOK)、関数定義で定義された位置の順序に従う必要があります。すべての引数には言及が必要だと思います。必須の引数が最初になり、次にオプションの引数が続き、次に名前と値のペアが続きます。vararginMathWorksは、キーワードを使用しないことも推奨していますがnarginnargoutそれでも有用です。

  • projectorこの場合、クラス要件は、などのカスタムクラスにすることができます。
  • 必須の引数にはデフォルト値がない場合があります(つまり、デフォルト値がないために既知です)。
  • オプションの引数にはデフォルト値が必要です(つまり、デフォルト値があるため既知です)。
  • デフォルト値は、同じ引数検証に合格できる必要があります。つまり、のデフォルト値はzeros(3)、文字ベクトルであるはずの引数のデフォルト値としては機能しません。
  • 名前と値のペアは、内部で構造体に変換される引数に格納されます。ここでは、これを呼び出しています( Pythonoptionsのように、構造体を使用してキーワード引数を渡すことができることを示唆しています)。kwargs
  • 非常にうまく、関数呼び出しでタブを押すと、名前と値の引数が引数のヒントとして表示されるようになりました。(完了のヒントに興味がある場合は、MATLABのfunctionSignatures.json機能も調べることをお勧めします)。

したがって、この例でinputDirは、デフォルト値が指定されていないため、は必須の引数です。また、1xNの文字ベクトルである必要があります。そのステートメントと矛盾するかのように、MATLABは、提供された引数を変換して、変換された引数が成功するかどうかを確認しようとすることに注意してください。たとえば、97:122として渡すと、と(つまり)が渡されます。逆に、ベクトルではないため、機能しません。また、文字を指定するときに文字列を失敗させたり、uint8を要求するときにdoubleを失敗させたりすることを忘れてください。これらは変換されます。この「柔軟性」を回避するには、さらに深く掘り下げる必要があります。inputDirinputDir == char(97:122)inputDir == 'abcdefghijklmnopqrstuvwxyz'zeros(3)

次に、値がまたは'foo'のみの名前と値のペアを指定します。'bar''baz'

MATLABには多数のmustBe...検証関数があり(入力 mustBeを開始し、Tabキーを押して何が利用できるかを確認します)、独自の関数を作成するのは簡単です。独自に作成する場合、たとえば、ユーザーがダイアログをキャンセルした場合uigetdirに返される入力とは異なり、入力が一致しない場合、検証関数はエラーを返す必要があります。0個人的には、MATLABの規則に従い、検証関数を呼び出す ので、自然数のmustBe...ような関数があり、実際に存在するファイルを確実に渡すことができます。mustBeNaturalmustBeFile

'Angle'値がスカラーのdoubleまたは整数でなければならない名前と値のペアを指定します。たとえば、引数example(pwd, 'foo', 'baz', 'Angle', [30 70])にベクトルを渡したため、機能しません。Angle

あなたはその考えを理解します。ブロックには多くの柔軟性がありargumentsます-多すぎても少なすぎても、私は思います-しかし、単純な関数の場合、それは速くて簡単です。inputParser検証の複雑さに対処するためにvalidateattributes、、、などの1つ以上に依存する場合もありますがassert、私は常に最初に物事をargumentsブロックに詰め込もうとします。見苦しくなってきたら、argumentsブロックやアサーションなどをやろうと思います。

于 2020-02-11T22:58:11.110 に答える
6

個人的には、多くのStatistics Toolbox関数(kmeans、pca、svmtrain、ttest2など)で使用されるプライベートメソッドから派生したカスタム関数を使用しています。

内部ユーティリティ関数であるため、リリースごとに何度も変更され、名前が変更されました。MATLABのバージョンに応じて、次のファイルのいずれかを探してみてください。

%# old versions
which -all statgetargs
which -all internal.stats.getargs
which -all internal.stats.parseArgs

%# current one, as of R2014a
which -all statslib.internal.parseArgs

文書化されていない関数と同様に、保証はなく、今後のリリースで予告なしにMATLABから削除される可能性があります...とにかく、誰かが古いバージョンの関数をgetargsとしてFileExchangeに投稿したと思います。

この関数は、有効なパラメーター名のセットとそのデフォルト値を使用して、パラメーターを名前/値のペアとして処理します。解析されたパラメーターを個別の出力変数として返します。デフォルトでは、認識されない名前/値ペアはエラーを発生させますが、追加の出力でそれらをサイレントにキャプチャすることもできます。関数の説明は次のとおりです。

$MATLABROOT\toolbox\stats\stats\+internal\+stats\parseArgs.m

function varargout = parseArgs(pnames, dflts, varargin)
%
% [A,B,...] = parseArgs(PNAMES, DFLTS, 'NAME1',VAL1, 'NAME2',VAL2, ...)
%   PNAMES   : cell array of N valid parameter names.
%   DFLTS    : cell array of N default values for these parameters.
%   varargin : Remaining arguments as name/value pairs to be parsed.
%   [A,B,...]: N outputs assigned in the same order as the names in PNAMES.
%
% [A,B,...,SETFLAG] = parseArgs(...)
%   SETFLAG  : structure of N fields for each parameter, indicates whether
%              the value was parsed from input, or taken from the defaults.
%
% [A,B,...,SETFLAG,EXTRA] = parseArgs(...)
%   EXTRA    : cell array containing name/value parameters pairs not
%              specified in PNAMES.

例:

function my_plot(x, varargin)
    %# valid parameters, and their default values
    pnames = {'Color', 'LineWidth', 'LineStyle', 'Title'};
    dflts  = {    'r',           2,        '--',      []};

    %# parse function arguments
    [clr,lw,ls,txt] = internal.stats.parseArgs(pnames, dflts, varargin{:});

    %# use the processed values: clr, lw, ls, txt
    %# corresponding to the specified parameters
    %# ...
end

この例の関数は、次のいずれかの方法で呼び出すことができます。

>> my_plot(data)                                %# use the defaults
>> my_plot(data, 'linestyle','-', 'Color','b')  %# any order, case insensitive
>> my_plot(data, 'Col',[0.5 0.5 0.5])           %# partial name match

いくつかの無効な呼び出しとスローされたエラーは次のとおりです。

%# unrecognized parameter
>> my_plot(x, 'width',0)
Error using [...]
Invalid parameter name: width.

%# bad parameter
>> my_plot(x, 1,2)
Error using [...]
Parameter name must be text.

%# wrong number of arguments
>> my_plot(x, 'invalid')
Error using [...]
Wrong number of arguments.

%# ambiguous partial match
>> my_plot(x, 'line','-')
Error using [...]
Ambiguous parameter name: line.

inputParser:

他の人が述べているように、関数入力を解析するための公式に推奨されるアプローチは、inputParserクラスを使用することです。必須入力、オプションの位置引数、名前/値パラメーターの指定など、さまざまなスキームをサポートします。また、入力の検証(引数のクラス/タイプやサイズ/形状のチェックなど)を実行することもできます。

于 2010-05-06T12:53:06.893 に答える
5

この問題に関するローレンの有益な投稿を読んでください。コメントセクションを読むことを忘れないでください...-このトピックにはかなりの数の異なるアプローチがあることがわかります。それらはすべて機能するので、好みの方法を選択することは、実際には個人の好みと保守性の問題です。

于 2010-05-05T20:09:29.940 に答える
3

私は次のような自家製のボイラープレートコードの大ファンです:

function TestExample(req1, req2, varargin)
for i = 1:2:length(varargin)
    if strcmpi(varargin{i}, 'alphabet')
        ALPHA = varargin{i+1};

    elseif strcmpi(varargin{i}, 'cutoff')
        CUTOFF = varargin{i+1};
        %we need to remove these so seqlogo doesn't get confused
        rm_inds = [rm_inds i, i+1]; %#ok<*AGROW>

    elseif strcmpi(varargin{i}, 'colors')
        colors = varargin{i+1};
        rm_inds = [rm_inds i, i+1]; 
    elseif strcmpi(varargin{i}, 'axes_handle')
        handle = varargin{i+1};
        rm_inds = [rm_inds i, i+1]; 
    elseif strcmpi(varargin{i}, 'top-n')
        TOPN = varargin{i+1};
        rm_inds = [rm_inds i, i+1];
    elseif strcmpi(varargin{i}, 'inds')
        npos = varargin{i+1};
        rm_inds = [rm_inds i, i+1];
    elseif strcmpi(varargin{i}, 'letterfile')
        LETTERFILE = varargin{i+1};
        rm_inds = [rm_inds i, i+1];
    elseif strcmpi(varargin{i}, 'letterstruct')
        lo = varargin{i+1};
        rm_inds = [rm_inds i, i+1];
    end
end

このようにして、ほとんどのMatlab関数が引数を取る方法とほぼ同じである「オプション」と値のペアをシミュレートできます。

お役に立てば幸いです。

意思

于 2010-05-05T19:19:23.650 に答える
1

Jonasのアイデアに基づいて、私が試しているソリューションは次のとおりです。

function argStruct = NameValuePairToStruct(defaults, varargin)
%NAMEVALUEPAIRTOSTRUCT Converts name/value pairs to a struct.
% 
% ARGSTRUCT = NAMEVALUEPAIRTOSTRUCT(DEFAULTS, VARARGIN) converts
% name/value pairs to a struct, with defaults.  The function expects an
% even number of arguments to VARARGIN, alternating NAME then VALUE.
% (Each NAME should be a valid variable name.)
% 
% Examples: 
% 
% No defaults
% NameValuePairToStruct(struct, ...
%    'foo', 123, ...
%    'bar', 'qwerty', ...
%    'baz', magic(3))
% 
% With defaults
% NameValuePairToStruct( ...
%    struct('bar', 'dvorak', 'quux', eye(3)), ...
%    'foo', 123, ...
%    'bar', 'qwerty', ...
%    'baz', magic(3))
% 
% See also: inputParser

nArgs = length(varargin);
if rem(nArgs, 2) ~= 0
   error('NameValuePairToStruct:NotNameValuePairs', ...
      'Inputs were not name/value pairs');
end

argStruct = defaults;
for i = 1:2:nArgs
   name = varargin{i};
   if ~isvarname(name)
      error('NameValuePairToStruct:InvalidName', ...
         'A variable name was not valid');
   end
   argStruct = setfield(argStruct, name, varargin{i + 1});  %#ok<SFLD>
end

end
于 2010-05-06T09:40:08.513 に答える
1

Jonasの答えに触発されましたが、よりコンパクトです。

function example(varargin)
  defaults = struct('A',1, 'B',magic(3));  %define default values

  params = struct(varargin{:});
  for f = fieldnames(defaults)',
    if ~isfield(params, f{1}),
      params.(f{1}) = defaults.(f{1});
    end
  end

  %now just access them as params.A, params.B
于 2014-01-13T18:48:19.387 に答える
1

昔から使ってprocess_options.mいます。安定していて使いやすく、さまざまなmatlabフレームワークに含まれています。ただし、パフォーマンスについては何も知りません–より高速な実装がある可能性があります。

私が最も気に入っている機能process_optionsunused_args戻り値です。これを使用して、入力引数をサブプロセスなどの引数のグループに分割できます。

また、デフォルト値を簡単に定義できます。

最も重要なこと:process_options.m通常、使用すると、読み取り可能保守可能なオプション定義が得られます。

コード例:

function y = func(x, y, varargin)

    [u, v] = process_options(varargin,
                             'u', 0,
                             'v', 1);
于 2014-09-23T08:08:38.520 に答える
1

parsepvpairsMATLABの財務ツールボックスにアクセスできる場合は、これをうまく処理するという気の利いた関数があります。これは、3つの引数、予想されるフィールド名、デフォルトのフィールド値、および受け取った実際の引数を取ります。

たとえば、MATLABでHTML図形を作成し、「url」、「html」、および「title」という名前のオプションのフィールド値のペアを取得できる関数を次に示します。

function htmldlg(varargin)
    names = {'url','html','title'};
    defaults = {[],[],'Padaco Help'};
    [url, html,titleStr] = parsepvpairs(names,defaults,varargin{:});

    %... code to create figure using the parsed input values
end
于 2016-12-07T18:10:32.110 に答える
1

MATLAB 2019b以降を使用している場合、関数で名前と値のペアを処理する最良の方法は、「関数の引数の検証を宣言する」を使用することです。

function result = myFunction(NameValueArgs)
arguments
    NameValueArgs.Name1
    NameValueArgs.Name2
end

% Function code
result = NameValueArgs.Name1 * NameValueArgs.Name2;

end

参照:https ://www.mathworks.com/help/matlab/ref/arguments.html

于 2021-08-12T10:56:26.387 に答える
0
function argtest(varargin)

a = 1;

for ii=1:length(varargin)/2
    [~] = evalc([varargin{2*ii-1} '=''' num2str(varargin{2*ii}) '''']);
end;

disp(a);
who

もちろん、これは正しい割り当てをチェックしませんが、それは単純であり、役に立たない変数はとにかく無視されます。また、数値、文字列、配列に対してのみ機能し、行列、セル、構造に対しては機能しません。

于 2010-08-11T13:17:20.013 に答える
0

私は今日これを書くことになり、それからこれらの言及を見つけました。鉱山では、オプションに構造体と構造体の「オーバーレイ」を使用しています。新しいパラメータを追加できないことを除いて、基本的にsetstructfields()の機能を反映しています。setstructfields()が自動的に行うのに対し、再帰のオプションもあります。struct(args {:})を呼び出すことにより、ペアの値のセル配列を取り込むことができます。

% Overlay default fields with input fields
% Good for option management
% Arguments
%   $opts - Default options
%   $optsIn - Input options
%       Can be struct(), cell of {name, value, ...}, or empty []
%   $recurseStructs - Applies optOverlay to any existing structs, given new
%   value is a struct too and both are 1x1 structs
% Output
%   $opts - Outputs with optsIn values overlayed
function [opts] = optOverlay(opts, optsIn, recurseStructs)
    if nargin < 3
        recurseStructs = false;
    end
    isValid = @(o) isstruct(o) && length(o) == 1;
    assert(isValid(opts), 'Existing options cannot be cell array');
    assert(isValid(optsIn), 'Input options cannot be cell array');
    if ~isempty(optsIn)
        if iscell(optsIn)
            optsIn = struct(optsIn{:});
        end
        assert(isstruct(optsIn));
        fields = fieldnames(optsIn);
        for i = 1:length(fields)
            field = fields{i};
            assert(isfield(opts, field), 'Field does not exist: %s', field);
            newValue = optsIn.(field);
            % Apply recursion
            if recurseStructs
                curValue = opts.(field);
                % Both values must be proper option structs
                if isValid(curValue) && isValid(newValue) 
                    newValue = optOverlay(curValue, newValue, true);
                end
            end
            opts.(field) = newValue;
        end
    end
end

命名規則「defaults」と「new」を使用する方がおそらく良いと思います:P

于 2011-09-11T06:05:13.670 に答える
0

JonasとRichieCottonをベースにした機能を作りました。これは、両方の機能(柔軟な引数または制限付き、つまりデフォルトに存在する変数のみが許可されることを意味します)と、構文糖衣構文および健全性チェックなどの他のいくつかの機能を実装します。

function argStruct = getnargs(varargin, defaults, restrict_flag)
%GETNARGS Converts name/value pairs to a struct (this allows to process named optional arguments).
% 
% ARGSTRUCT = GETNARGS(VARARGIN, DEFAULTS, restrict_flag) converts
% name/value pairs to a struct, with defaults.  The function expects an
% even number of arguments in VARARGIN, alternating NAME then VALUE.
% (Each NAME should be a valid variable name and is case sensitive.)
% Also VARARGIN should be a cell, and defaults should be a struct().
% Optionally: you can set restrict_flag to true if you want that only arguments names specified in defaults be allowed. Also, if restrict_flag = 2, arguments that aren't in the defaults will just be ignored.
% After calling this function, you can access your arguments using: argstruct.your_argument_name
%
% Examples: 
%
% No defaults
% getnargs( {'foo', 123, 'bar', 'qwerty'} )
%
% With defaults
% getnargs( {'foo', 123, 'bar', 'qwerty'} , ...
%               struct('foo', 987, 'bar', magic(3)) )
%
% See also: inputParser
%
% Authors: Jonas, Richie Cotton and LRQ3000
%

    % Extract the arguments if it's inside a sub-struct (happens on Octave), because anyway it's impossible that the number of argument be 1 (you need at least a couple, thus two)
    if (numel(varargin) == 1)
        varargin = varargin{:};
    end

    % Sanity check: we need a multiple of couples, if we get an odd number of arguments then that's wrong (probably missing a value somewhere)
    nArgs = length(varargin);
    if rem(nArgs, 2) ~= 0
        error('NameValuePairToStruct:NotNameValuePairs', ...
            'Inputs were not name/value pairs');
    end

    % Sanity check: if defaults is not supplied, it's by default an empty struct
    if ~exist('defaults', 'var')
        defaults = struct;
    end
    if ~exist('restrict_flag', 'var')
        restrict_flag = false;
    end

    % Syntactic sugar: if defaults is also a cell instead of a struct, we convert it on-the-fly
    if iscell(defaults)
        defaults = struct(defaults{:});
    end

    optionNames = fieldnames(defaults); % extract all default arguments names (useful for restrict_flag)

    argStruct = defaults; % copy over the defaults: by default, all arguments will have the default value.After we will simply overwrite the defaults with the user specified values.
    for i = 1:2:nArgs % iterate over couples of argument/value
        varname = varargin{i}; % make case insensitive
        % check that the supplied name is a valid variable identifier (it does not check if the variable is allowed/declared in defaults, just that it's a possible variable name!)
        if ~isvarname(varname)
          error('NameValuePairToStruct:InvalidName', ...
             'A variable name was not valid: %s position %i', varname, i);
        % if options are restricted, check that the argument's name exists in the supplied defaults, else we throw an error. With this we can allow only a restricted range of arguments by specifying in the defaults.
        elseif restrict_flag && ~isempty(defaults) && ~any(strmatch(varname, optionNames))
            if restrict_flag ~= 2 % restrict_flag = 2 means that we just ignore this argument, else we show an error
                error('%s is not a recognized argument name', varname);
            end
        % else alright, we replace the default value for this argument with the user supplied one (or we create the variable if it wasn't in the defaults and there's no restrict_flag)
        else
            argStruct = setfield(argStruct, varname, varargin{i + 1});  %#ok<SFLD>
        end
    end

end

要旨としてもご利用いただけます。

また、実際の名前付き引数(Pythonに似た構文、例:myfunction(a = 1、b ='qwerty'))に関心がある場合は、InputParserを使用します(Matlabの場合のみ、Octaveユーザーはv4.2まで待つ必要があります。少なくとも、 InputParser2というラッパーを試すことができます)。

また、ボーナスとして、常に入力する必要はなくargstruct.yourvar、直接使用する必要がある場合は、 JasonSによるyourvar次のスニペットを使用できます。

function varspull(s)
% Import variables in a structures into the local namespace/workspace
% eg: s = struct('foo', 1, 'bar', 'qwerty'); varspull(s); disp(foo); disp(bar);
% Will print: 1 and qwerty
% 
%
% Author: Jason S
%
    for n = fieldnames(s)'
        name = n{1};
        value = s.(name);
        assignin('caller',name,value);
    end
end
于 2014-06-10T10:05:48.960 に答える