我有这样的功能:
f(x) = { x if 0 < x < n
{ n-x if n < x < 2*n
Run Code Online (Sandbox Code Playgroud)
如何在MATLAB中输入此功能?
最好的方法是将它放在子函数或嵌套函数中,或者放在一个单独的m文件中:
function y = f(x)
n = 4; %// Or whatever your N is
if x <= 0 || x >= 2*n
y = 0;
elseif x < n
y = x;
else
y = n-x;
end
end
Run Code Online (Sandbox Code Playgroud)
或者,更一般地说,何时x
是矢量/矩阵,
function y = f(x)
y = x;
y(x >= n) = n-x(x >= n);
y(x <= 0 | x >= 2*n) = 0;
end
Run Code Online (Sandbox Code Playgroud)
或者,您当然可以将其n
作为参数传递:
function y = f(x, n)
...
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用此匿名函数:
f = @(x) (x>0 & x<n).*x + (x>=n & x<=2*n).*(n-x);
Run Code Online (Sandbox Code Playgroud)
再次,可选,通过n
:
f = @(x,n) ...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
59 次 |
最近记录: |