kwargify

版本 1.1.0.0 (2.6 KB) 作者: Benjamin
simple lightweight workaround to get keyword arguments (kwargs) in Matlab
53.0 次下载
更新时间 2015/8/17

Specify default values in your function. Pass a structure of variables that you wish to overwrite, and kwargify will update that. You can decide to overwrite some, all, or none of the values. You can also pass additional values.
It works by basically overwriting the fields of your default options structure with any that are specified in your charge structure.

Please see the github page for full info: https://github.com/drbenvincent/kwargify

Example usage

%% Example 1
% I want to call myFunction, but I just want to use the defaul options and not specify any kwargs
myFunction(42,[])

%% Example 2
% Now I want to overwrite the default value for b, and add an extra one d, so I will specify my kwargs here. You can call them opts though if you prefer.
kwargs.b = 5;
kwargs.d = 4;

% call myFunction with these kwargs
myFunction(42,kwargs)

myFunction is your function which will have the following general form:

function myFunction(exampleRequiredArgument,kwargs)
% If you want your function to work with kwargs, then you have to specify
% default options in a structure here. These will be overwritten by
% fieldnames in the kwargs structure. If kwargs are not provided (ie
% kwargs=[]) then the detaults are used.

% Default options
opts.a = 1;
opts.b = 2;
opts.c = 3;

% display the default opts
display('defaults are:'), opts

% This is where the magic happens ~~~
opts = kwargify(opts,kwargs);
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

% display the updated opts
display('after using ''kwargify'': '), opts

% DO SOMETHING USEFUL HERE USING VALUES IN (opts) STRUCTURE
display(exampleRequiredArgument+ opts.b)

return

引用格式

Benjamin (2024). kwargify (https://github.com/drbenvincent/kwargify), GitHub. 检索来源 .

MATLAB 版本兼容性
创建方式 R2014b
兼容任何版本
平台兼容性
Windows macOS Linux
类别
Help CenterMATLAB Answers 中查找有关 Scope Variables and Generate Names 的更多信息

Community Treasure Hunt

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

Start Hunting!

无法下载基于 GitHub 默认分支的版本

版本 已发布 发行说明
1.1.0.0

updated description

1.0.0.0

要查看或报告此来自 GitHub 的附加功能中的问题,请访问其 GitHub 仓库
要查看或报告此来自 GitHub 的附加功能中的问题,请访问其 GitHub 仓库