Given a matrix A = [2 5 7; 4 1 8], write a for loop that will replace all the even numbers with 0.
Show older comments
I'm looking for something using a for loop (probably nested) and possibly mod(A,2) to determine the even numbers
What I tried: It took me a while to figure out how to format mod, but once I did I started with: for b=mod(A,2) I think tried to add a logical function (such as b==0) but it kept giving me errors. The closest thing that I could write that made sense in my head was:
for b=mod(A,2);
if b==0
A(b)=0
end
end
I would then get the error: Subscript indices must either be real positive integers or logicals.
I also couldn't figure out how to size a matrix to be the same size as a different matrix.
3 Comments
James Tursa
on 7 Oct 2016
What have you done so far? Do you know how to write a loop? Do you know how to write if-else-end conditional code? What specific problems are you having with your current code?
Marc Jakobi
on 7 Oct 2016
Have you made an attempt that you could post here?
Sydney
on 7 Oct 2016
Accepted Answer
More Answers (1)
Andrei Bobrov
on 7 Oct 2016
A(rem(A,2)==0)=0;
or with loop
for ii = 1:numel(A)
if rem(A(ii),2) == 0
A(ii) == 0;
end
end
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!