Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a MATLAB program in a script file that asks the user to input a vector of

ID: 2266174 • Letter: W

Question

Write a MATLAB program in a script file that asks the user to input a vector of arbitrary length. The program then counts the number of total, positive, and negative elements. The program needs to count the number of even positive and negative elements. The program should display the results in sentence form, i.e., “The vector has XX element(s): XX element(s) is/are positive and XX element(s) is/are negative. Positive XX and negative XX element(s) are even.”, where XX stands for the corresponding number of elements. Please try your code for the following vectors: [1 3 4 -5 -6 -7] and [0 0 4 5 6 -5 -13 -14 -100].

Explanation / Answer

MATLAB CODE:

function []=even_odd(x)

Number_of_elements=length(x);

Positive_Num=0; % Let Positive Numbers count to be zero

Negative_Num=0; % Let Negative Numbers count to be zero

Positive_Even=0; %Let Positive Even Numbers count to be zero

Negative_Even=0; % Let Nevative Even Numbers count to be zero

Number_of_Zeros=0;

for i=1:1:Number_of_elements

if x(i)>0

Positive_Num=Positive_Num+1;

if mod(x(i),2)==0

Positive_Even=Positive_Even+1;

end

elseif x(i)==0

Number_of_Zeros=Number_of_Zeros+1;

else

Negative_Num=Negative_Num+1;

if mod(x(i),2)==0

Negative_Even=Negative_Even+1;

end

end

end

fprintf('The vector has %d element(s). %d element(s) is/are positive and %d element(s) is/ are negative. Positive %d and Negative %d element(s) are even. ',...

Number_of_elements,Positive_Num,Negative_Num,Positive_Even,Negative_Even)

end

OUTPUT:

>> x=[0 0 4 5 6 -5 -13 -14 -100];

>> even_odd(x)

The vector has 9 element(s).

3 element(s) is/are positive and 4 element(s) is/ are negative.

Positive 2 and Negative 2 element(s) are even.

>>

>> x= [1 3 4 -5 -6 -7];

>> even_odd(x)

The vector has 6 element(s).

3 element(s) is/are positive and 3 element(s) is/ are negative.

Positive 1 and Negative 1 element(s) are even.

>>

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote