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

2 Ansichten (letzte 30 Tage)
Tomas Marhan
Tomas Marhan am 13 Okt. 2019
Kommentiert: dpb am 16 Okt. 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 Kommentare
dpb
dpb am 16 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Fabio Freschi
Fabio Freschi am 13 Okt. 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

Andrei Bobrov
Andrei Bobrov am 16 Okt. 2019
lo = logical(mod(vect,2));
vect_even = vect(~lo);
vect_odd = vect(lo);

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by