How to find all the even numbers in a vector?

Say we have a vector x=[ 1 1 2 2 2 2 3 3 3 3 4 4 4 ] and I want to find all the even numbers but subtract is by 1 so that the vector will only contain odd numbers. How would I do that?

Answers (1)

Try this:
% Create sample data.
x = [ 1 1 2 2 2 2 3 3 3 3 4 4 4 ]
% Find indices where x is even:
evenIndices = rem(x, 2) == 0
% Extract only the even numbers into a new vector.
allTheEvenNumbers = x(evenIndices)
% Now subtract 1 from that.
allTheEvenNumbers = allTheEvenNumbers - 1
In the command window, you'll see:
x =
1 1 2 2 2 2 3 3 3 3 4 4 4
evenIndices =
0 0 1 1 1 1 0 0 0 0 1 1 1
allTheEvenNumbers =
2 2 2 2 4 4 4
allTheEvenNumbers =
1 1 1 1 3 3 3

4 Comments

But I'd like to put the "AllTheEvenNumbers" vector back into my original x vector. Like so:
x=[ 1 1 2 2 2 2 3 3 3 3 4 4 4 ] %code to find all even vectors and subtract it by 1 x=[1 1 1 1 1 1 3 3 3 3 3 3 3]
Bold numbers are the one that were originally an even number turned into an odd.
This sounds like homework. Is it? I hope I did not just do your homework for you. When you said "the vector" it was not clear which vector, the original or the even-only vector, you meant. Here is code that does what you are now asking for:
% Create sample data.
x = [ 1 1 2 2 2 2 3 3 3 3 4 4 4 ]
% Find indices where x is even:
evenIndices = rem(x, 2) == 0
% Replace the even numbers.
x(evenIndices) = x(evenIndices) - 1
In the command window:
x =
1 1 2 2 2 2 3 3 3 3 4 4 4
evenIndices =
0 0 1 1 1 1 0 0 0 0 1 1 1
x =
1 1 1 1 1 1 3 3 3 3 3 3 3
Thanks that was exactly what I was looking for! And yes it is a part of a homework assignment but this particular code is just a small part to a larger code.
Please mark the best answer as "Accepted" when you're done with a discussion. Also, next time, tag the post as "homework" so we can answer appropriately and don't put you at risk of your instructor or plagiarism detectors some schools use finding out that you just had us solve the problem. We wouldn't want you to get in trouble.

Sign in to comment.

Categories

Asked:

on 15 Aug 2015

Commented:

on 15 Aug 2015

Community Treasure Hunt

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

Start Hunting!