How to skip parameters in a function call

30 ビュー (過去 30 日間)
Dominik Hildebrand
Dominik Hildebrand 2021 年 7 月 7 日
コメント済み: Star Strider 2021 年 7 月 7 日
Hello,
i'd like to make a function that can be called even if only a part of its input parameters are defined in the call.
I.e.:
Function definition is something along this lines:
function [ret] = fun(a, b, c, d, e)
if ~exist('a','var')
% parameter a does not exist, so default it to something
a = 0;
end
if ~exist('b','var')
...
ret = [a,b,c,d,e];
return;
The function call should work something like this:
test_call_1 = fun(a=1,b=2,d=3,e=4); (here parameter c is not specified)
test_call_2 = fun(e=4); (here only parameter e is specified)
My function is already able to initialize any missing parameters with default values. I know about using "~" to specify that a parameter is skipped. However, this only works for defining the function, not when calling it (as is required here).
Any help is highly appriciated :)

採用された回答

Star Strider
Star Strider 2021 年 7 月 7 日
See the documentation section on Support Variable Number of Inputs for a demonstration of how to do that.
  4 件のコメント
Dominik Hildebrand
Dominik Hildebrand 2021 年 7 月 7 日
Thank you again for your help :D
I feel your solution is as good as it gets, but for sake of completness ill include my final "draft" as well:
function [ ret ] = fun(a, b, c, d)
default_param = 0;
if ~exist('a','var') || isempty(a)
a = default_param;
end
if ~exist('b','var') || isempty(b)
b = default_param;
end
if ~exist('x','var') || isempty(x)
c = default_param;
end
if ~exist('c','var') || isempty(c)
d = default_param;
end
ret = [a,b,c,d];
return;
Star Strider
Star Strider 2021 年 7 月 7 日
As always, my pleasure!
Thank you!
Noted.
.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by