用其他值替换矩阵中的值 [英] Replace values in matrix with other values

查看:94
本文介绍了用其他值替换矩阵中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有整数的矩阵,我需要将所有2的出现都替换为-5.最有效的方法是什么?我是按照下面的方法做的,但是我敢肯定还有更优雅的方法.

I have a matrix with integers and I need to replace all appearances of 2 with -5. What is the most efficient way to do it? I made it the way below, but I am sure there is more elegant way.

a=[1,2,3;1,3,5;2,2,2]
ind_plain = find(a == 2)
[row_indx col_indx] = ind2sub(size(a), ind_plain)
for el_id=1:length(row_indx)
    a(row_indx(el_id),col_indx(el_id)) = -5;
end

我不是循环,而是寻找类似的东西:a(row_indx,col_indx)= -5,这不起作用.

Instead of loop I I seek for something like: a(row_indx,col_indx) = -5, which does not work.

推荐答案

find. 改用逻辑索引:

a(a == 2) = -5

如果要搜索矩阵是否等于inf,则应使用

In case of searching whether a matrix is equal to inf you should use

a(isinf(a)) = -5

一般情况是:

Mat(boolMask) = val

其中Mat是您的矩阵,boolMask是另一个logical值矩阵,而val是分配值

where Mat is your matrix, boolMask is another matrix of logical values, and val is the assignment value

这篇关于用其他值替换矩阵中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆