Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 用其他值替换矩阵中的值_Matlab_Matrix - Fatal编程技术网

Matlab 用其他值替换矩阵中的值

Matlab 用其他值替换矩阵中的值,matlab,matrix,Matlab,Matrix,我有一个带整数的矩阵,我需要用-5替换2的所有外观。最有效的方法是什么?我是按照下面的方式做的,但我相信还有更优雅的方式 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

我有一个带整数的矩阵,我需要用-5替换2的所有外观。最有效的方法是什么?我是按照下面的方式做的,但我相信还有更优雅的方式

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\u indx,col\u indx)=-5,这不起作用。

find
在这种情况下不需要。 改用逻辑索引:

a(a == 2) = -5
在搜索矩阵是否等于
inf
时,应使用

a(isinf(a))=-5

一般情况是:

Mat(boolMask)=val

Mat
是您的矩阵时,
boolMask
是另一个
逻辑值的矩阵,而
val
是赋值

试试以下方法:

a(a==2) = -5;
稍长一点的版本是

ind_plain = find(a == 2);
a(ind_plain) = -5;
换句话说,您可以直接使用线性索引对矩阵进行索引,而无需使用
ind2sub
转换它们——非常有用!但正如上面所演示的,如果使用布尔矩阵对矩阵进行索引,则会变得更短


顺便说一句,如果(通常情况下)您对获取转储到控制台的语句结果不感兴趣,则应该在语句后加上分号。

如果您正在更改向量中的值,则Martin B的方法很好。然而,要在矩阵中使用它,您需要获得线性索引

我找到的最简单的解决方案是使用
changem
函数。非常容易使用:

mapout=changem(Z,newcode,oldcode)
在您的情况下:
newA=changem(a,5,-2)


更多信息:

这里是映射工具箱中的
changem
的一个简单、未经优化、可能很慢的实现

function mapout = changem(Z, newcode, oldcode)
% Idential to the Mapping Toolbox's changem
% Note the weird order: newcode, oldcode. I left it unchanged from Matlab.
    if numel(newcode) ~= numel(oldcode)
        error('newcode and oldcode must be equal length');
    end

    mapout = Z;

    for ii = 1:numel(oldcode)
        mapout(Z == oldcode(ii)) = newcode(ii);
    end
end

@Andrey,你能不能也建议一下,当使用isinf函数在矩阵中搜索无穷大时,如何使用它?(PlusOne)很好的解决方案,但值得一提的是,它需要映射工具箱。