27 views (last 30 days)
vidushi Chaudhary on 19 May 2020
Answered: Geoff Hayes on 19 May 2020
%Write a function called max_sum that takes v as a row vector of numbers, & n,a postive integer as inputs.The function needs to find n consecutive
%elements of v whose sum is the largest possible.If multiple such sequence exists in v,max_sum returns first one.The function returns summa & index
%,the index of first element of n consecutive ones.If n>v,then the function returns summa as 0 & index=-1.
%Example-[summa,index]=max_sum([1 2 3 4 5 4 3 2 1],3])
%summa=13
%index=4
function [summa,index]=max_sum(v,n)
total=0;
if n>v
summa=0;
index=-1;
else
for ii=1:length(v)
jj=ii+(n-1);
if jj<=length(v)
total=[total,sum(v(ii):v(jj))]; %Here I'm trying to create a row vector with sum of consecutive n integers
end
end
[summa,index]=max(total);
end
end

KSSV on 19 May 2020
Your jj gets equals to 9. Where as your v is of size 1*8. Code tries to extract v(9) so the error.
vidushi Chaudhary on 19 May 2020
The code is working now,but it's giving incorrect value of summa(It is giving 12 for the above example..).What is wrong?

Geoff Hayes on 19 May 2020
vidushi - the problem is with this line
total=[total,sum(v(ii):v(jj))];
and in particular the inputs to the sum function. Here you are providing two integers (based on the input array) and using the : colon to produce an array of elements between these two. So if your two integers are 1 and 8, then
>> 1:8
ans =
1 2 3 4 5 6 7 8
which is an array of eight integers which isn't what you want. Instead, you want to extract from v a subset or sub-array of consecurtive elements of length 3. So you need to do
total=[total,sum(v(ii:jj))];