write a program that counts odd and even positive numbers from a vector in matlab

You can count even and odd numbers from a vector in MATLAB using the following code:

main.m
% Define the vector of positive numbers
A = [2 4 5 7 8 11 14 15];

% Initialize variables for counting even and odd numbers
num_even = 0;
num_odd = 0;

% Loop through each element in the vector
for ii = 1:length(A)
    % Check if the number is positive and even
    if A(ii) > 0 && rem(A(ii), 2) == 0
        num_even = num_even + 1;
    % Check if the number is positive and odd
    elseif A(ii) > 0 && rem(A(ii), 2) == 1
        num_odd = num_odd + 1;
    end
end

% Display the counts of even and odd numbers
disp(['Number of even positive numbers: ' num2str(num_even)]);
disp(['Number of odd positive numbers: ' num2str(num_odd)]);
636 chars
22 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