I am trying to write a function that takes both an input vector and scalar (v and n respectively). It needs to output the maximum value of the sum of n consecutive integers of v, as well as the index of the first term in v.

15 ビュー (過去 30 日間)
I am trying to write a function that takes both an input vector and scalar (v and n respectively). It needs to output the maximum value of the sum of n consecutive integers of v, as well as the index of the first term in v.
Here is an example of how the function should work:
>> [total ind] = maxval([1 2 3 4 5 4 3 2 1],3)
total = 13
ind = 4
Here is the code that I have so far:
I do not understand how to get the function to replace a current maximum with a newly calculated larger maximum. I'm also confused on how to find the index and how to construct the "else" statement.
function [total, ind] = maxval(v, n)
total = 0;
ind = 0;
for a = 1:length(v)
for b = a:(a+n)
if sum(v(b)) > v % at this point im confused :/
total = sum(v(b));
ind = v(a);
else
total = sum(v(b))
end
end
end
end

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 3 月 18 日
編集済み: Ameer Hamza 2020 年 3 月 18 日
There is no need to use a for loop.
v = [1 2 3 4 5 4 3 2 1];
n = 3;
sums = movsum(v, n, 'Endpoints', 'discard');
[~, idx] = max(sums);
max_sum = sums(idx);
  3 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 3 月 18 日
I too got to know about it somewhere here on another question. I agree this makes the code more readible in many cases.
James Metz
James Metz 2020 年 3 月 18 日
Thanks so much for all your help!

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

その他の回答 (1 件)

James Metz
James Metz 2020 年 3 月 18 日
For anyone still confused by the above answer, here is the complete code:
function [max_sum, idx] = maxval(v, n)
sums = movsum(v, n, 'Endpoints', 'discard');
[~, idx] = max(sums);
max_sum = sums(idx);
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by