You can count even and odd numbers from a vector in MATLAB using the following code:
main.m636 chars22 lines
In this code, you first define the vector of positive numbers A
. Then, you initialize two variables num_even
and num_odd
to count the number of even and odd positive numbers in the vector, respectively.
Next, you loop through each element in the vector using a for
loop. For each element, you check if it is positive and even using the rem
function, which returns the remainder of a division operation. If the remainder of A(ii)/2
is 0, then the number is even. Similarly, if the remainder is 1, then the number is odd.
If the number is even, you increment the num_even
counter. If the number is odd, you increment the num_odd
counter.
Finally, you display the counts of even and odd numbers using the disp
function. The num2str
function is used to convert the count variables from numbers to strings, so that they can be concatenated with the display text.
gistlibby LogSnag