gpt4 book ai didi

matlab - 我的功能的不确定输入数量

转载 作者:行者123 更新时间:2023-12-02 07:48:27 24 4
gpt4 key购买 nike

我最近遇到一个问题,我应该定义一个输入数量不确定的函数,即输入数量可能会因实际情况而异。我应该使用二维数组还是其他什么?我不知道 struct2cell 是否有帮助以及它是否真的有效。

有没有人知道执行此操作的最佳方法?

我可能不是很清楚,所以如果有任何需要澄清的地方,请告诉我。

谢谢

最佳答案

有几种方法可以解决这个问题:

如果给定参数的含义与上下文无关,则使用可选的输入参数,但如果在某些情况下,需要额外的输入。

function out = myFun(first,second,third,fourth)

%# first is always needed
if nargin < 1 || isempty(first)
error('need nonempty first input')
end

%# second is optional
if nargin < 2 || isempty(second)
second = defaultValueForSecondWhichCanBeEmpty;
end

%# etc

您可以将此函数称为 out = myFun(1,[],2,3),即为不需要的输入传递一个空数组。


如果两个输入意味着该函数以一种方式使用,三个输入意味着该函数以另一种方式使用(甚至输入意味着不同的东西),请使用 VARARGIN

function out = myFun(varargin)

%# if 2 inputs, it's scenario 1, with 3 it's scenario 2
switch nargin
case 2
firstParameter = varargin{1};
secondParameter = varargin{2};
scenario = 1;
case 3
firstParameter = varargin{1}; %# etc
otherwise
error('myFun is only defined for two or three inputs')
end

最后,您还可以将输入作为 parameterName/parameterValue 对传递。参见示例 this question关于如何处理此类输入。

关于matlab - 我的功能的不确定输入数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5215244/

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