根据条件改变矩阵的元素 [英] Change elements of matrix based on condition
本文介绍了根据条件改变矩阵的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有矩阵A:
A =
1 2 3
4 5 6
对于每个元素 x< 2
,为每个元素添加10,
x> 5
,为每个元素添加20和
2< = x< = 5
,添加30。
For every element x<2
, add 10,
for every element x>5
, add 20, and
for every element 2<=x<=5
, add 30.
因此对于我的示例矩阵A,我需要得到以下结果矩阵B:
So for my example matrix A, I need to end up with the following matrix B:
B =
11 32 33
34 35 26
我需要能够以一般方式执行此操作,因为实际矩阵将非常大。有什么建议么?我可以使用 IF
声明吗?
I need to be able to do this in a general way, since the actual matrix will be quite large. Any suggestions? Can I use the IF
statement?
推荐答案
你不需要一个 IF
你需要逻辑索引:
IndexOfLessThan2 = A < 2;
IndexOfGreaterThan5 = A > 5;
IndexBtw2and5 = ~(IndexOfLessThan2 | IndexOfGreaterThan5);
A = A + IndexOfLessThan2*10 + IndexOfGreaterThan5*20 + IndexBtw2and5*30;
这篇关于根据条件改变矩阵的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文