How do I use for loops and if statements to find numbers in a two dimensional array and replace them?
Ältere Kommentare anzeigen
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 Kommentar
BCLAcowgirl#1
am 18 Feb. 2018
Akzeptierte Antwort
Weitere Antworten (3)
Roger Stafford
am 18 Feb. 2018
Bearbeitet: Roger Stafford
am 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 Kommentar
BCLAcowgirl#1
am 18 Feb. 2018
Bearbeitet: BCLAcowgirl#1
am 18 Feb. 2018
Image Analyst
am 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
am 3 Okt. 2021
0 Stimmen
I have one array and in this array detected number in this array so how to detected number in array?
1 Kommentar
Image Analyst
am 3 Okt. 2021
Use == (if they're integers) or ismembertol() if they're floating point numbers.
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

