如何在Matlab中使用匿名函数过滤数组?

Mar*_*n08 2 matlab

我想编写一个过滤数组的函数,最好是匿名函数.用文字说话很难,但是就像这样:

f = @(x) { if (x > 1) x+1 }; 
a = [ 1, 2, 3];
f(a) % 
==> [ 1 3 4]
Run Code Online (Sandbox Code Playgroud)

我想要的关键点是:

  • 希望函数接收数字或字符串
  • 但是当给定一个数组时,该函数将自身应用于数组中的每个元素并返回另一个数组.

这类似于函数log()的工作方式:

>> log(1) 
ans =
      0 
>> log([1,2,3])
ans =
      0    0.6931    1.0986
Run Code Online (Sandbox Code Playgroud)

谢谢

gno*_*ice 6

你可以这样做:

f = @(x) x + (x > 1);
Run Code Online (Sandbox Code Playgroud)