首页 > 解决方案 > 匿名函数中的 if-then-else

问题描述

我试图在匿名函数中使用某种 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)

我正在寻找这样的东西:

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

我也试过这个,但是,显然我不允许将等号放入匿名函数中。

new_cellarray = cellfun(@(x) x(x > 0) = 1, cellarray, 'UniformOutput', false)
new_cellarray = cellfun(@(x) x(x < 0) = -1, cellarray, 'UniformOutput', false)

标签: matlabanonymous-functioncell-array

解决方案


您可以使用内置函数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);

推荐阅读