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

조회 수: 2 (최근 30일)
Tomas Marhan
Tomas Marhan 2019년 10월 13일
댓글: dpb 2019년 10월 16일
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