在MATLAB中有选择地指定可选函数参数 [英] Specifying optional function parameters selectively in MATLAB

查看:422
本文介绍了在MATLAB中有选择地指定可选函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Matlab中的默认参数

Possible Duplicate:
Default Arguments in Matlab

我有一个带有大约7个参数的函数.其中3个为必填项,其余4个为可选参数.我只想传递前3个和最后一个参数.我该怎么做?

I have a function with about 7 parameters to be passed. 3 of them are mandatory and the rest 4 are optional parameters. I want to pass only the first 3 and the last parameter. How do I do this?

让我们说函数是: 函数[...] = fun(a,b,c,d,e,f,g)

Let us say that the function is: function[...] = fun(a, b, c, d, e, f, g)

a,b,c-必需的输入.

a, b, c - required inputs.

d,e,f,g-可选输入.

d, e, f, g - optional inputs.

我想调用fun并传递a,b,c和g的值.

I want to call fun and pass values for a, b, c and g.

在R中,我可以用非常整齐的方式指定它,例如: fun(a = 1,b = 4,c = 5,g = 0);

In R, I can specify this in a very neat way like: fun(a=1, b=4, c=5, g=0);

matlab中的等效语法是什么?

What is the equivalent syntax in matlab?

推荐答案

不幸的是,没有办法做到这一点.您必须为不想传递的参数显式传递空值,并且需要检查函数中的条件以查看是否传递了参数以及该参数是否为空.像这样:

Unfortunately, there is no way to do this. You have to explicitly pass empty values for the parameters you do not want to pass, and you need to check that condition in your function to see, if a parameter has been passed or not, and if it is empty or not. Something like this:

function fun(a, b, c, d, e, f, g)
    if nargin<3
        error('too few parameters');
    end
    if nargin<4 || isempty(d)
        d = default_value;
    end
    % and so on...
end

% call
fun(a, b, c, [], [], g);

最后,将可选参数收集到一个结构中并检查其字段可能会更容易:

In the end it might be easier to collect the optional parameters into one structure and check its fields:

function fun(a, b, c, opt)
    if nargin<3
        error('too few parameters');
    end
    if nargin>3
        if ~isfield(opt, 'd')
            opt.d = default_value;
        end
    end
end

% call
opt.g = g;
fun(a, b, c, opt);

调用该函数更容易,并且您不必指定空参数.

It is easier to call the function, and you do not have to specify empty parameters.

这篇关于在MATLAB中有选择地指定可选函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆