Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

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?

like image 625
JavascriptLoser Avatar asked Nov 27 '25 04:11

JavascriptLoser


2 Answers

If you just want to change all the 4s to 5s then:

x(x==4)=5

basically x==4 will result in a logical matrix with 1s 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 1s are and change them all to 5s.

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
like image 63
Dan Avatar answered Nov 29 '25 20:11

Dan


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.

like image 36
Nras Avatar answered Nov 29 '25 19:11

Nras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!