Changing matrix elements using a for loop in matlab
I am having a few problems getting MATLAB to do what I want.
Let's say I have a matrix x = [1 2 3 4; 1 4 4 5; 6 4 1 4]
I am trying to write code that will go through the matrix and change every 4 to 5, so it changes the input matrix
I've tried several 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 from looking at the artboard that the element value did change, but the x (matrix) value remained the same.
How do I get the result I'm looking for?
source to share
If you just want to change everything 4
to 5
, then:
x(x==4)=5
x==4
will basically result in a boolean matrix with 1
everywhere been 4
in x
:
[0 0 0 1
0 1 1 0
0 1 0 1]
We then use a boolean index to only affect the values x
where these are 1
, and change them all to 5
c.
If you want to do this using a loop (which I highly recommend against), you can do this:
for index = 1:numel(x)
if x(index) == 4
x(index) = 5;
end
end
source to share
Short answer to achieve what you want:
x(x==4) = 5
The answer to the question of why your code doesn't do what you expected: You change item
to 5. But this element is a new variable, it does not point to the same element in your matrix x
. Hence, the original matrix x
remains unchanged.
source to share