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

6 次查看(过去 30 天)
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 个评论
dpb
dpb 2019-10-16
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.

请先登录,再进行评论。

回答(2 个)

Fabio Freschi
Fabio Freschi 2019-10-13
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

Andrei Bobrov
Andrei Bobrov 2019-10-16
lo = logical(mod(vect,2));
vect_even = vect(~lo);
vect_odd = vect(lo);

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by