How to create function with name-value pair arguments?
    117 ビュー (過去 30 日間)
  
       古いコメントを表示
    
Hello. I want to create the function like
function [x1, x2] = fun('name',varargin,'name',[..],'name',[..])
How i can do it? 
1 件のコメント
  Simon Skillen
 2024 年 3 月 26 日
				
      編集済み: Walter Roberson
      
      
 2024 年 3 月 27 日
  
			I'd use the function argument method as described in https://de.mathworks.com/help/matlab/matlab_prog/function-argument-validation-1.html 
採用された回答
  Walter Roberson
      
      
 2019 年 12 月 21 日
        
      編集済み: Walter Roberson
      
      
 2019 年 12 月 21 日
  
      Note: in R2019b and later, see the new arguments keyword
0 件のコメント
その他の回答 (3 件)
  Voss
      
      
 2024 年 3 月 27 日
        fcn('name','booey','professional_life','noine','personal_life',2,'tooth_size','XXXL')
fcn('name','Fred','home_planet','Mars','temper_quotient',Inf)
function fcn(varargin)
args = reshape(varargin,2,[]);
p = struct(args{:})
% do something with structure p
end
0 件のコメント
  Christopher Rowley
 2021 年 12 月 1 日
        To provide some sample code on how to do this with data in a structure, here is an example. We are have two variables 'x' and 'z' that are stored in structure 'params', and a test function looks to compute x+z +5. I have a simple check that the name is type character, but you can add more, or tailor to your needs. The function would look like:
function y = testfunction( params, varargin)
% set up name-value pairs for varargin.
for i = 1:2:length(varargin) % work for a list of name-value pairs
    if ischar(varargin{i}) % check if is character
        params.(varargin{i}) = varargin{i+1}; % override or add parameters to structure.
    end
end
y = params.z + params.x + 5;
And to try it, use:
params.x = 5;
params.z = 10;
testfunction( params) % try function
testfunction( params, 'x', 1) % try changing x from what it was set in the params structure.
In this example, the results should be 20, and 16, where the difference comes from the fact that x was decreased by 4 in the second function call. 
0 件のコメント
  Black Woods
 2022 年 12 月 17 日
        function db=name_value_pairs(varargin)
if isempty(varargin) || mod(length(varargin),2)==1
    db={};
    return
end
jj=1;
for ii=1:2:length(varargin)
     if isa(varargin{ii},'char')
        db{jj,1}=varargin{ii};db{jj,2}=varargin{ii+1};jj=jj+1;
     else         
         db={};
         return
     end
end    
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!





