# How do I use for loops and if statements to find numbers in a two dimensional array and replace them?

50 views (last 30 days)
BCLAcowgirl#1 on 18 Feb 2018
Commented: Image Analyst on 3 Oct 2021
I need to replace all the negative numbers in A=[1 2 4; 3 2 -1; 2 4 5; -2 -1 10] with zeros using for loops and if statements.
Below is the coding I have, but it doesn't do anything. Please, advise me on what I'm doing wrong.
for i=A
if i<0
A(i)=0;
end
end
##### 1 CommentShowHide None
BCLAcowgirl#1 on 18 Feb 2018
URGENT need to know before Thurs, Feb 22nd.

Star Strider on 18 Feb 2018
In your homework assignment that requires for loops and an if block, you need two nested loops, one looping through the rows and another the columns. In the innermost loop, use the if statement to test and replace the negative values of ‘A’, not the loop indices (that in MATLAB must be integers greater than zero, so a test for negative values of them will always fail).
There are more straightforward ways to do this, one being:
A = [1 2 4; 3 2 -1; 2 4 5; -2 -1 10];
A = A .* (A>0)
A =
1 2 4
3 2 0
2 4 5
0 0 10
I don’t mind showing you that solution, since you can’t use it in your assignment.
##### 2 CommentsShowHide 1 older comment
Star Strider on 18 Feb 2018
You need to test for the value of ‘A(i,j)’ not the subscripts of ‘A(i,j)’.
I provided my solution as a hint as to how best for you to approach it.

### More Answers (3)

Roger Stafford on 18 Feb 2018
Edited: Roger Stafford on 18 Feb 2018
Use the "linear" form of the array:
for i = 1:length(A(:))
if A(i) < 0 % <- [Corrected]
A(i) = 0;
end
end
or you can do this:
t = A<0;
A(t(:)) = 0;
##### 1 CommentShowHide None
BCLAcowgirl#1 on 18 Feb 2018
Edited: BCLAcowgirl#1 on 18 Feb 2018
This is what I get when I type in that:

Image Analyst on 18 Feb 2018
Close, but you need to loop from 1 to numel(A) and you need to check if A(i) < 0, not if i < 0.
A=[1 2 4; 3 2 -1; 2 4 5; -2 -1 10]
for i = 1 : numel(A)
if A(i) < 0
A(i) = 0;
end
end
A

Patel Keyur on 3 Oct 2021
I have one array and in this array detected number in this array so how to detected number in array?
##### 1 CommentShowHide None
Image Analyst on 3 Oct 2021
Use == (if they're integers) or ismembertol() if they're floating point numbers.

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by