How do I write a function to find 4 consecutive numbers in a square matrix which would give the largest product?

1 view (last 30 days)
I think I should be using for loops but I'm very confused how to write them in this case.
function y=hardstuff(a)
x=size(a)
if x(1)~=x(2)
error 'Matrix not square'
elseif x(1)<=3
error 'Matrix too small'
end
b=a(1,:)
c=length(b)
d=1
for i=1:4
d=d*a(i)
end
  1 Comment
Cedric
Cedric on 1 Nov 2013
Edited: Cedric on 1 Nov 2013
If it's for a homework, with small size arrays, you could start sorting elements ( doc sort ), and then implement some loop starting from the largest element, and figuring out if the current element plus the next 3 are consecutive numbers.

Sign in to comment.

Answers (1)

Matt J
Matt J on 1 Nov 2013
Edited: Matt J on 1 Nov 2013
Hint: here's a loop-free method to obtain all products of 4 consecutive elements,
T= conv2(log(a),[1 1 1 1].','valid');
T=real(exp(T));
There is no assumption here that the elements are positive.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!