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

Write a MATLAB function max_product that takes v a vector and n, a positive inte

ID: 3798048 • Letter: W

Question

Write a MATLAB function max_product that takes v a vector and n, a positive integer, as inputs and computes the largest product of n consecutive elements of v. It returns the product and the index of the element of v that is the first term of the product. If there are multiple such products in v, the function must return the one with the smallest starting index. As an example, the following call >> [product, ind] = max_product([1 2 2 1 3 1],3); will assign 6 to product and 3 to ind since the max 3-term product in the input vector is 2*1*3. If v has fewer than n elements, the function returns 0 and -1, respectively.

Explanation / Answer

function [product , ind ] = max_product(v,n)

cmp2 = 1;

cmp1 = 1;

pos = 1;

if(n <= length(v))

for i = 1:n

cmp2 = cmp2 * v(i);

end

for j = 2 : length(v) + 1 - n

cmp1 = 1;

for k = 0 : n - 1

cmp1 = cmp1 * v(j + k);

end

if(cmp1 > cmp2)

cmp2 = cmp1;

pos = j;

end

end

product = cmp2;

ind = pos;

else

product = 0;

ind = -1;

end

end

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