matlab - 匿名函数中的 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)
解决方案
您可以使用内置函数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);
推荐阅读
- python - 打印数据框时如何不截断列(显示所有列)
- javascript - 打字稿类型错误属性不存在
- apache-kafka - 无效值:null 用于必填字段:\"null\",架构类型:STRING\n\tat
- python - 如何在 python 3 中制作矩形选择工具?
- php - dockerizing phpunit 测试时的最佳实践
- python - Django 事务不适用于原始 SQL 查询
- maven - 如何在 Maven 项目中制作包?
- java - 从 ArrayList 获取最新的唯一参数
- sql - 获取最高工资SQL的部门名称
- mysql - 删除没有root权限或mysql用户的MySQL8 SELECT ... INTO FILE文件