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

*** Write a MATLAB function called maxproduct that takes a matrix A and a positi

ID: 3832948 • Letter: #

Question

*** Write a MATLAB function called maxproduct that takes a matrix A and a positive integer scalar n as inputs and computes the largest product of n adjacent elements in the same direction in A. That is, we are looking for products of consecutive elements in the same row, column, diagonal or reverse diagonal. The function must return an n-by-2 matrix containing the row and column indexes ordered first by row and then by column. If no such product exists, the function returns the empty array. For example, valid outputs for a max product of 3 neighbors in four different matrices might be [2 2; 2 3; 2 4] or [1 1; 2 1; 3 1] or [3 5; 4 4; 5 3] or [4 2; 5 3; 6 4]. If there are multiple products with the same maximum value, return the first one you find. (Inspired by Project Euler.)

Explanation / Answer


function B = maxproduct(A,n)


[r,c] = size(A);
if n>r && n>c
    B = [];                                  % cannot be solved
    return
end
global L;
L = zeros(1,4);                            % [product, home-row, home-col, direction]
for i=1:r                          
    for j=1:c-n+1
      check(A(i,j:j+n-1),[i,j,1]);           % row, right case
    end
end
for i=1:r-n+1                      
    for j=1:c
      check(A(i:i+n-1,j),[i,j,2]);           % column, down case
    end
end
for i=1:r-n+1
    for j=1:c-n+1
      S=A(i:i+n-1,j:j+n-1);
      check(diag(S),[i,j,3]);                % diagonal, down case
      check(diag(flip(S,2)),[i,j,4]);        % reverse diagonal, down case
    end
end
i=L(2); j=L(3);                            % reconstruct coordinates
switch L(4)                                
    case 1, B = [ones(n,1)*i,(j:j+n-1)'];    
    case 2, B = [(i:i+n-1)',ones(n,1)*j];
    case 3, B = [(i:i+n-1)',(j:j+n-1)'];
    case 4, B = [(i:i+n-1)',(j+n-1:-1:j)'];
end
end

function check(V,d)
global L;
p = prod(V);
if p>L(1)                                % if new product larger than any previous
    L = [p,d];                             % then update product, home and direction
end
end