In: Electrical Engineering
Assume the vector AM contains an even number of elements.
Develop a MATLAB script that asks the user for the vector AM and
once the vector is found to contain an even number of elements,
divide the product of its even elements by the sum of its odd
elements without using the MATLAB functions prod or sum. Store the
result in a variable called PDS. If AM is found to contain an odd
number of elements, display an error message and prompt the user
again for a vector with an even number of elements.
ANSWER:
the below is trhe copyable code with respect to the given data;
copyable code:
%myScript.m
%get the number of elements from the user.
nn=input("Enter the vector length:");
%check the element count
if(mod(nn,2)==1)
%if element count is not even then print error
error("number of elements is odd");
%end
end
%declare the vector AM
AM=zeros(nn,1);
fprintf("Enter the vector elements:\n");
%read the vector elements
for kk=1:nn
AM(kk)=input("Enter the element:");
end
%create prodEven
prodEven=1;
%create variable sumOdd
sumOdd=0;
%use loop to find the even number product and odd number sum
for kk=1:nn
%product of even number
if(mod(AM(kk),2)==0)
prodEven = prodEven * AM(kk);
%sum of odd number
else
sumOdd= sumOdd + AM(kk);
end
end
%define PDS
PDS =0;
%find the PDS
if(sumOdd>0)
PDS = prodEven/sumOdd;
end
%display PDS
fprintf("The result is %f\n",PDS);
SAMPLE OUTPUT: