简体   繁体   中英

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.

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]

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

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.

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:

x(x==4)=5

basically x==4 will result in a logical matrix with 1 s everywhere there was a 4 in x :

[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.

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 . Hence the original matrix x remains unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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