gpt4 book ai didi

matlab - 正确使用波浪号运算符作为输入参数

转载 作者:太空宇宙 更新时间:2023-11-03 19:19:38 32 4
gpt4 key购买 nike

功能:

我的 MATLAB 函数有一个输出和几个输入参数,其中大部分是可选的,即:

output=MyFunction(arg1,arg2,opt1,opt2,...,optN)

我想做什么:

我只想将 arg1、arg2 和最后一个可选输入参数 optN 提供给函数。我按如下方式使用波浪号运算符:

output=MyFunction(str1,str2,~,~,...,true)

不良结果:

这给出了以下错误信息:

Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

错误指向第一个波浪号后的逗号,但老实说我不知道​​该怎么做。

问题识别:

  • 我使用 MATLAB 2013b,它支持波浪号运算符。

  • 根据 MA​​TLAB 的文档,上述函数调用应该有效:

    You can ignore any number of function inputs, in any position in the argument list. Separate consecutive tildes with a comma...

  • 我想有一些解决方法,例如使用 '' 或 [] 作为输入,但我真的很想了解如何正确使用 '~',因为实际上省略输入允许我使用 exist () 检查函数的输入参数时。

如果您需要我提供更多信息,请告诉我。

非常感谢!

最佳答案

波浪号仅用于函数声明。 Matlab 的 mlint 建议用 ~ 替换未使用的参数。结果是一个像这样声明的函数 function output = MyFunction(a, b, ~, c)。这是一种非常糟糕的做法。

由于您有一个参数可选的函数,因此您必须使用空参数调用该函数 output=MyFunction(str1,str2,[],[],...,true)

更好的方法是使用 varargin 参数声明函数,并为不同的输入准备函数:

function output = MyFunction(varargin)

if nargin == 1
% Do something for 1 input
elseif nargin == 2
% Do something for 3 inputs
elseif nargin == 3
% Do something for 3 inputs
else
error('incorrect number of input arguments')
end

甚至可以按如下方式声明您的函数:

function output = MyFunction(arg1, arg2, varargin)

上面的声明将告诉 Matlab 您至少需要两个参数。

请参阅nargin 的文档here .

...和varargin 的文档here

关于matlab - 正确使用波浪号运算符作为输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25204074/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com