[英]Not enough input arguments in function
I have a function of this form 我有这种形式的功能
function [g] = g(i,j)
k=1;
if i==0
g=0;
elseif i==k
g=j;
end
And I don't want the second line in the code. 我不希望代码中的第二行。 Instead I want the function to read k from the main program.
相反,我希望函数从主程序中读取k。 I don't want to write
我不想写
function [g] = g(i,j,k)
instead, because in this way I will have to write g as a function of i,j and k in the code of the main program. 相反,因为这样我将不得不在主程序的代码中写出g作为i,j和k的函数。 Is there another way ?
还有另外一种方法吗?
You can use an anonymous function to create a closure . 您可以使用匿名函数来创建闭包 。 Define your function as
将您的功能定义为
function [g] = g(i,j,k)
if i==0
g=0;
elseif i==k
g=j;
end
end
And then in your main script you can do something like 然后在你的主脚本中你可以做类似的事情
k=1;
g2 = @(i,j)g(i,j,k);
And now you can call g2
the way you were calling g
before but k
will be 1
and it will be defined in your main script instead of in your function. 现在你可以按照你之前调用
g
的方式调用g2
,但k
将为1
,它将在你的主脚本而不是你的函数中定义。
Or you could even skip k
completely and define: 或者你甚至可以完全跳过
k
并定义:
g1 = @(i,j)g(i,j,1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.