简体   繁体   English

在matlab中使用for循环更改矩阵的元素

[英]Changing the elements of a matrix using a for loop in matlab

I'm having a few issues getting MATLAB to do what I want. 我有几个问题让MATLAB做我想做的事。

say I have a matrix x = [1 2 3 4; 1 4 4 5; 6 4 1 4] 说我有一个矩阵x = [1 2 3 4; 1 4 4 5; 6 4 1 4] x = [1 2 3 4; 1 4 4 5; 6 4 1 4]

I'm trying to write code that will go through the matrix and change each 4 to a 5, so it modifies the input matrix 我正在尝试编写将遍历矩阵并将每个4更改为5的代码,因此它会修改输入矩阵

I've tried a few things: 我尝试过几件事:

while index <= numel(x)
    if index == 4
        index = 5;
    end
    index = index + 1;
end


for item = x
    if item == 4
        item = 5;
    end
end

the simplest thing i tried was 我尝试过的最简单的事情就是

for item = x
    if item == 4
        item = 5;
    end
end

i noticed by looking at the workspace that the value of item did indeed change but the value of x (the matrix) stayed the same. 我注意到通过查看工作区,项的值确实发生了变化,但x(矩阵)的值保持不变。

How do I get the output that i'm looking for? 如何获得我正在寻找的输出?

If you just want to change all the 4 s to 5 s then: 如果您只想将所有4秒更改为5秒,那么:

x(x==4)=5

basically x==4 will result in a logical matrix with 1 s everywhere there was a 4 in x : 基本上x==4将产生一个逻辑矩阵,其中x4 ,每个都是1

[0 0 0 1
 0 1 1 0
 0 1 0 1]

We then use logical index to only affect the values of x where those 1 s are and change them all to 5 s. 然后我们使用逻辑索引仅影响那些1x的值,并将它们全部更改为5秒。

If you wanted to do this using a loop (which I highly recommend against) then you can do this: 如果你想使用循环(我强烈建议反对)这样做,那么你可以这样做:

for index = 1:numel(x)
    if x(index) == 4
        x(index) = 5;
    end
end

Short answer to achieve what you want: 简短的回答,实现你想要的:

x(x==4) = 5

Answer to why your code doesn't do what you expected: You are changing the item to a 5. But that item is a new variable, it does not point to the same item in your matrix x . 回答为什么你的代码不符合你的预期:你正在将item更改为5.但是该项目是一个新变量,它不指向矩阵x的相同项目。 Hence the original matrix x remains unchanged. 因此原始矩阵x保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM