ProgramingTip

MATLAB에서 함수 인수의 이름 / 값 쌍을 처리하는 방법

bestdevel 2020. 11. 17. 20:41
반응형

MATLAB에서 함수 인수의 이름 / 값 쌍을 처리하는 방법


말할 인수를 이름 / 값 쌍으로 사용하는 함수가 있습니다.

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과 함께 제공되는 도우미 함수가 있습니까?


내 옵션에 구조를 사용하는 것을 선호합니다. 이렇게하면 쉽게 저장하고 쉽게 정의 할 수 있습니다. 또한 전체가 다소 콤팩트 해입니다.

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

InputParser 는이를 도와줍니다. 자세한 내용은 함수 입력 구문 분석 을 참조하십시오.


나는 이것에 대해 몇 시간 동안 야크를 할 수 있었지만 여전히 일반적인 Matlab 서명 처리에 대한 좋은보기를 가지고 있지 않습니다. 하지만 여기에 몇 가지 조언이 있습니다.

먼저 입력 유형의 유효성을 검사하기 위해 자유롭고 공정한 접근 방식을 취하십시오. 발신 신뢰하십시오. 강력한 유형 테스트를 자바와 같은 정적 언어가 필요합니다. Matlab의 모든 곳에서 유형 안전을 실행하면 LOC 및 실행 시간의 상당 부분이 사용자 영역에서 실행 테스트 및 강제 변환에 할당되어 Matlab의 많은 힘과 개발 속도를 사용하게됩니다. . 나는 어려운 방법으로 배웠다.

API 서명 (명령 줄 대신 다른 함수에서 호출 할 함수)의 경우 varargin 대신 단일 Args 인수를 사용하는 것이 좋습니다. 그런 다음 varargin 시그니처에 대해 쉼표로 구분 된 목록으로 변환하지 여러 인수간에 무제한 수 있습니다. Jonas가 말한 것처럼 굴곡은 매우 편리합니다. 또한 모든 것과 nx2 {이름, 가치; ...} 셀 사이에 멋진 동형이 사용, 내부에서 내부적으로 사용하려는 변환하는 몇 가지 함수를 수 있습니다.

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

inputParser를 사용하든 다른 예제와 같이 고유 한 이름 / 유효 파서 롤링하든, 이름 / 유효 시그니처가있는 함수의 맨 위에서 호출 할 별도의 표준 함수로 패키지화하십시오. 작성하기 쉬운 데이터 구조의 추가 목록을 수락하고 인수 구문 분석 호출은 가독성을 높이고 상용구 복사 및 널 넣기를 코드 함수 서명 선언처럼 보일 것입니다.

다음은 파싱 호출의 모습입니다.

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

그리고 여기에 이름 / val 구문 분석을 구현하는 함수가 있습니다. 속을 비우고 inputParser, 고유 한 유형 규칙 등으로 대체 할 수 있습니다. nx2 셀 규칙이 잘 읽을 수있는 소스 코드를 읽고 생각합니다. 그것을 유지하는 것을 고려하십시오. nx2 셀은 일반적으로 수신 코드에서 처리하는 것이 더 편리하지만 nx2 셀은 사용하여 리터럴을 구성하는 것이 더 편리합니다. (구조는 각 줄에 ", ..."연속이 필요하며 셀 값이 비스 칼라 구조로 확장되지 않도록 보호합니다.)

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

Matlab에서 일류 유형이 아니라는 것은 매우 유감입니다.


개인적으로 저는 많은 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

문서화되지 않은 기능과 서비스가 제공되지 않을 것입니다. 어쨌든가 누군가 파일 교환에 getargs 로 이전 버전을 게시하고 생각 합니다.

이 함수는 이름과 함께 사용하는 매개 변수 이름을 사용하여 처리 변수 이름 / 값을 처리합니다. 구문 분석 된 매개 변수를 별도의 출력 변수로 반환합니다. 기본적으로 인식 할 수없는 이름 / 값 쌍은 오류를 발생시키는 자동 만 추가 출력에서 ​​함께 할 수도 있습니다. 다음은 기능 설명입니다.

$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


이 문제에 대한 Loren의 유익한 게시물읽어보세요 . -이 내용에 대한 접근 방식이 상당히 주제에 대해 알게 될 것입니다. 모두 작동 방식을 선호하는 방법을 선택하는 방식으로 개인적인 취향과 유지 관리의 문제입니다.


나는 다음과 같은 자체 개발 보일러 플레이트 코드의 더 큰 팬입니다.

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 함수가 인수를 취하는 방식과 거의 동일한 '옵션', 값 쌍을 시뮬레이션 할 수 있습니다.

도움이 되길 바랍니다.

의지


다음은 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

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

parsepvpairsMATLAB의 재무 도구 상자에 액세스 할 수있는 경우에 잘 처리하고 멋진 함수를 사용할 수 있습니다. 세 개의 인수, 예상 필드 이름, 기본 필드 값 및 수신 된 실제 인수가 필요합니다.

예를 들어, 다음은 MATLAB에서 HTML Figure를 생성하고 '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

나이부터 사용하고 있습니다. 안정적이고 사용하기 쉬우 며 다양한 MATLAB 프레임 워크에 포함되었습니다. 하지만 성능에 모든 것입니다. 더 빠른 구현이 가능합니다.process_options.m

내가 가장 좋아하는 기능 process_optionsunused_args반환 값으로, 예를 들어 하위 프로세스에 대한 인수 그룹에서 입력 인수를 분할하는 데 사용할 수 있습니다.

그리고 문맥을 쉽게 정의 할 수 있습니다.

가장 중요한 : 사용 process_options.m보통은 결과 읽기유지 관리 옵션 정의.

예제 코드 :

function y = func(x, y, varargin)

    [u, v] = process_options(varargin,
                             'u', 0,
                             'v', 1);

function argtest(varargin)

a = 1;

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

disp(a);
who

물론 올바른 할당을 확인하고 무시하고 쓸모없는 변수는 무시합니다. 또한 숫자, 배열 및 배열에 작동하지만 작동하지 않습니다.


오늘이 글을 쓰고 나서이 언급을 찾았습니다. 광산은 옵션에 struct와 struct '오버레이'를 사용합니다. 새 매개 변수를 추가 할 수 없다는 점을 제외하고는 본질적으로 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


Jonas와 Richie Cotton을 기반으로 함수를 만들었습니다. 기능 (유연한 인수 또는 제한, 기본값에 존재하는 변수 만 허용됨)과 구문 설탕 및 온 전성 검사와 같은 몇 가지 다른 기능을 모두 구현합니다.

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없지만 직접 사용 하는 것을 원하지 않는 경우 Jason Syourvar 의 다음 코드 조각을 사용할 수 있습니다 .

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

참고 URL : https://stackoverflow.com/questions/2775263/how-to-deal-with-name-value-pairs-of-function-arguments-in-matlab

반응형