# max_product that t takes v as vector and n as positive integer

1 view (last 30 days)
Wasi von Deutschland on 22 May 2017
Commented: Andrei Bobrov on 24 May 2017
function [prodout,ind] = max_product(A,n)
A=0;
prodout = exp( conv(log(A),ones(1,n),'valid') );
if isreal(A), prodout=real(prodout);
end
Wasi von Deutschland on 22 May 2017

Stephen23 on 22 May 2017
Edited: Stephen23 on 24 May 2017
Method one: slidefun: Download Jos' excellent FEX submission slidefun, then you just need:
>> max_product = @(v,n)max(slidefun(@prod,n,v,'forward'))
>> [p,x] = max_product([1,2,2,1,3,1],3)
p = 6
x = 3
>> [p,x] = max_product([1,2,3,4,5,6,7,8,9,10], 2)
p = 90
x = 9
Method two: toeplitz:
>> max_product = @(v,n)max(prod(toeplitz(v(n:-1:1),v(n:end)),1));
>> [p,x] = max_product([1,2,2,1,3,1],3)
p = 6
x = 3
>> [p,x] = max_product([1,2,3,4,5,6,7,8,9,10],2)
p = 90
x = 9
Wasi von Deutschland on 24 May 2017
if numel(v)<n
product=0;
ind=-1;
end
Wasi von Deutschland on 24 May 2017

Guillaume on 24 May 2017
Edited: Guillaume on 24 May 2017
Another possible way:
slide = toeplitz(v(1:n), v);
[product, ind] = max(prod(slide(:, n:end)));
##### 3 CommentsShow 1 older commentHide 1 older comment
Guillaume on 24 May 2017
For some reason, I'd inverted the order of the arguments to toeplitz.
Now fixed.
Stephen23 on 24 May 2017
+1 nice solution

Andrei Bobrov on 24 May 2017
Edited: Andrei Bobrov on 24 May 2017
max_product = @(A,n)max(exp(conv2(log(A(:)),ones(n,1),'valid')));
use:
>> [value,ii] = max_product([1 2 3 4 5 6 7 8 9 10], 2)
value =
90
ii =
9
>>
or with function hankel:
max_prod_hankel = @(A,n)max(prod(hankel(A(1:n),A(n:end))));
use:
>> [v,ii] = max_prod_hankel([1 2 3 4 5 6 7 8 9 10], 2)
v =
90
ii =
9
>>
Stephen23 on 24 May 2017
+1 for the hankel solution
Andrei Bobrov on 24 May 2017
Thank you Stephen.