The question is this:
Write a function called max_sum that takes v, a row vector of numbers, and n, a positive integer as inputs. The function needs to find the n consecutive elements of v whose sum is the largest possible. In other words, if v is [1 2 3 4 5 4 3 2 1] and n is 3, it will find 4 5 and 4 because their sum of 13 is the largest of any 3 consecutive elements of v. If multiple such sequences exist in v, max_sum returns the first one. The function returns summa, the sum as the first output argument and index, the index of the first element of the n consecutive ones as the second output. If the input n is larger than the number of elements of v, the function returns 0 as the sum and -1 as the index. Here are a few example runs:
[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],3) summa = 13 index = 4[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],2) summa = 9 index = 4
THe code I have written so far is as follows. My problem is that I am stuck on obtaining the largest possible sum. I wrote code and have been able to generate different sums in a vector but I am unable to put those answers in a vector themselves, by putting the answers in a vector I want to be able to use the 'max' function to obtain the largest sum. I haven't even touched finding the 'index' portion yet. Here's my code:
function [summa,index] = max_sum(v,n)r = 0;summa = zeros(1,length(v)); %% created a vector of 0's to length of v
if n > length(v) summa = 0; index = -1;else while n <= length(v) summa = sum(v(r+1:n)) % here need to replace 0's with the sum (with logical index) so i can choose max
r = r+1; n = n+1; end summa = max(summa); index = n;end%summa = v;
%index = n;
end
Again, I need some help because I am unsure how to proceed from here. Thank you.
Best Answer