Making a vector out of all even and odd numbers using for, if
6 views (last 30 days)
Show older comments
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
dpb
on 16 Oct 2019
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.
Answers (2)
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
Andrei Bobrov
on 16 Oct 2019
lo = logical(mod(vect,2));
vect_even = vect(~lo);
vect_odd = vect(lo);
0 Comments
See Also
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!