1 matlab anonymous-function optional-parameters
有没有办法在 MATLAB 中实现的匿名函数中使用可选参数?
请参阅以下示例:
foo = @(x,y)(x+y+12)
Run Code Online (Sandbox Code Playgroud)
可以y
是上述匿名函数中的可选参数,例如
foo = @(x,y?)(x+y+12)
Run Code Online (Sandbox Code Playgroud)
并且仅y
在提供时使用?
There's a concept in MATLAB called "variable-length input argument list", see varargin
. That can be used in anonymous functions in general, and specifically in your example:
foo = @(varargin) sum(cell2mat(varargin)) + 12;
foo(10) % 10 + 12
foo(10, 20) % 10 + 20 + 12
foo(10, 20, 30) % 10 + 20 + 30 + 12
Run Code Online (Sandbox Code Playgroud)
ans = 22
ans = 42
ans = 72
Run Code Online (Sandbox Code Playgroud)
varargin
is a cell array, so that we need to convert it to a regular (numeric) array. Then we just need to sum these values and add 12.
Of course, that solution only works, if all passed arguments are of some numeric type.
Hope that helps!
归档时间: |
|
查看次数: |
75 次 |
最近记录: |