Write a 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.

2 ビュー (過去 30 日間)
I can't seem to solve this. Anyone have any idea please?
  2 件のコメント
the cyclist
the cyclist 2017 年 8 月 31 日
People here are willing to help with homework, but you have to show an effort first. What have you tried? What are your ideas? Where are you stuck?
champions2015
champions2015 2017 年 9 月 1 日
編集済み: the cyclist 2017 年 9 月 1 日
function [product,ind]=max_product(v,n)
position=0;
mult=[];
if length(v)<n
product=0;
ind=-1;
end
for i=1:length(v)
while (length(v)-i+1)>=n
position=position+1;
j=i:(i+n-1)
M=v(j);
mult(position)=prod(M);
end
end
product=max(mult);
end
This is what I have got so far but i seem to be getting an error for M=v(j) each time (Matlab simply states it's invalid), as well as a simple output of 'j=1 2 3' which continues running non-stop. I have tried pre-allocating by creating 'N=zeros(size(v))'; however, this does not change anything.
Thanks in advance.

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

採用された回答

John D'Errico
John D'Errico 2017 年 9 月 1 日
編集済み: John D'Errico 2017 年 9 月 1 日
Ok. You made an effort. It is even a credible one. Not bad at all.
Some good things I see. You did not use prod as a variable name. You tested to see if n was too large, compared to the length of v. You used max to find the maximum product, so a "vectorized" tool there.
So, what did you do wrong? I'd suggest there is no need to put a while loop INSIDE the for loop. Just make the for loop stop at the right point. The while loop is what is screwing you up here.
Next, there is no need to create a counter called position! You already have that in the variable i.
You do need to preallocate mult. If not, your code will get really slow on some problems. So maybe this:
mult = zeros(1 , length(v) - n + 1);
Finally, you can get ind (the location of the max) from the max function too.
I won't completely re-write your code, because then it is my code, and you are close enough that you can solve the problem yourself. Drop the while loop. Set up your for loop like this:
for position=1:(length(v) - n + 1)
As you can see, I let the for loop increment position, so there is no need to use i as a loop variable.
Then use two output arguments from max at the end.
[product,ind] = max(mult);

その他の回答 (1 件)

Wu Hanting
Wu Hanting 2018 年 10 月 25 日
Besides, I think u are supposed to delete the ";" behind the "product = 0" and "ind = -1", or when testing condition of length(v)<n, there won't be any result.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by