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

3 ビュー (過去 30 日間)
Wasi von Deutschland
Wasi von Deutschland 2017 年 5 月 22 日
コメント済み: Andrei Bobrov 2017 年 5 月 24 日
My code that's not working. Please help
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

採用された回答

Stephen23
Stephen23 2017 年 5 月 22 日
編集済み: Stephen23 2017 年 5 月 24 日
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
  8 件のコメント
Wasi von Deutschland
Wasi von Deutschland 2017 年 5 月 24 日
if numel(v)<n
product=0;
ind=-1;
end
Wasi von Deutschland
Wasi von Deutschland 2017 年 5 月 24 日
I really appreciate your effort

サインインしてコメントする。

その他の回答 (2 件)

Guillaume
Guillaume 2017 年 5 月 24 日
編集済み: Guillaume 2017 年 5 月 24 日
Another possible way:
slide = toeplitz(v(1:n), v);
[product, ind] = max(prod(slide(:, n:end)));
  3 件のコメント
Guillaume
Guillaume 2017 年 5 月 24 日
For some reason, I'd inverted the order of the arguments to toeplitz.
Now fixed.
Stephen23
Stephen23 2017 年 5 月 24 日
+1 nice solution

サインインしてコメントする。


Andrei Bobrov
Andrei Bobrov 2017 年 5 月 24 日
編集済み: Andrei Bobrov 2017 年 5 月 24 日
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
>>
  2 件のコメント
Stephen23
Stephen23 2017 年 5 月 24 日
+1 for the hankel solution
Andrei Bobrov
Andrei Bobrov 2017 年 5 月 24 日
Thank you Stephen.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by