MATLAB Answers

0

Making a vector out of all even and odd numbers using for, if

Asked by Tomas Marhan on 13 Oct 2019
Latest activity Commented on by dpb
on 16 Oct 2019
Hello, I'm to make two vectors: one consisting of all even numbers and one of all the odd numbers from this vector from vector randi([1 50],1,50). I have to use only simple for and if cycles.
My attempt:
clear;
clc;
vect=randi([1 50],1,50);
a_odd=0;
a_even=0;
for a=1:length(vect);
if mod(vect(a),2)==0;
a_even=a_even+1;
vect_even(a_even)=vect(a);
else
a_odd=a_odd+1;
vect_odd(a_odd)=vect(a);
end
end
vect_even
vect_odd
Problem with this is, it always prints out different number of columns, when run few times and numbers in both vectors are in random order. So my question is whats wrong?

  3 Comments

What do you think is wrong? You'll have a random number of odd/even entries every time (unless you reset RNG to produce reproducible result; see the documentation for how to do that for testing/debugging) and the sequence will be in whatever order the values are in the original vector vect since you didn't sort them.
Given the HW restriction to use only for and if constructs, it's as reasonable an approach as any, other than you could have preallocated the two results vectors and then trimmed them to size for a slight runtime performance gain, but for tiny array sizes such as this it's not worth the extra code if you recognize the issue for larger problems.
The
numel(vect_even)+numel(vect_odd)
always totals 50 doesn't it? Or either by inspection or running a check on the results all elements of each are even/odd as supposed to be aren't they?
So, it would seem it meets the problem description as provided.
You can't control how many of each are going to be odd/even on each random trial so that concern is a nonstarter to begin with. You could format the output to put a fixed number per output record for "pretty" results, of course. Whether there's extra credit or not I don't know!!! :)
If you want the results (or an unspecified requirement) to have them ordered in a particular manner, that's another step as noted above and by others.

Sign in to comment.

2 Answers

Answer by Fabio Freschi on 13 Oct 2019

This happens because the original vector contains random numbers that change every time you run the code. So, also the number of odd and even entries change each run.
Regarding the sorting, they have the order of the original vector. If you want then increasing or decreasing, use sort

  0 Comments

Sign in to comment.


Answer by Andrei Bobrov
on 16 Oct 2019

lo = logical(mod(vect,2));
vect_even = vect(~lo);
vect_odd = vect(lo);

  0 Comments

Sign in to comment.