匿名函数中的if-then-else

And*_*ndi 2 matlab anonymous-function cell-array

我试图在匿名函数中使用某种if-then-else语句,该函数本身是的一部分cellfun。我有一个包含多个双矩阵的单元格数组。我想用+1替换所有双精度矩阵中的所有正数,并用-1替换所有负数。我想知道我是否可以使用匿名函数而不是编写一个单独的函数,然后再从中调用它cellfun

这是玩具示例:

mat = [2, 2, 0, -2; -2, 0, 0, 2; -2, 2, -2, 2]
cellarray = repmat({mat}, 3, 1)
Run Code Online (Sandbox Code Playgroud)

我正在寻找这样的东西:

new_cellarray = cellfun(@(x) if x > 0 then x = 1 elseif x < 0 then x = -1, cellarray, 'UniformOutput', false)
Run Code Online (Sandbox Code Playgroud)

我也尝试过此操作,但是,显然不允许我在匿名函数中添加等号。

new_cellarray = cellfun(@(x) x(x > 0) = 1, cellarray, 'UniformOutput', false)
new_cellarray = cellfun(@(x) x(x < 0) = -1, cellarray, 'UniformOutput', false)
Run Code Online (Sandbox Code Playgroud)

Cri*_*ngo 6

您可以使用内置函数sign,该函数根据其输入返回1、0或-1:

mat = [2, 2, 0, -2; -2, 0, 0, 2; -2, 2, -2, 2];
cellarray = repmat({mat}, 3, 1);
new_cellarray = cellfun(@sign, cellarray, 'UniformOutput', false);
Run Code Online (Sandbox Code Playgroud)