MATLAB Answers

## 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.

Asked by Ajai Kannan

### Ajai Kannan (view profile)

on 13 Feb 2019
Latest activity Commented on by Jan

### Jan (view profile)

on 30 Jun 2019
Accepted Answer by Guillaume

### Guillaume (view profile)

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.
I tried the follwing code but when there are two occurences for the same number, they both get removed in the same iteration and thus causes trouble.
function [summa, index] = max_sum(v,n)
summa = 0;
i = 0;
j = v;
m = [];
while i < n
summa = summa + max(j);
b = find(v==max(j));
m = [m b];
j = j(j<max(j));
i = i + 1 ;
end
t = sort(m);
index = t(1,1);
end

paul mary

### paul mary (view profile)

on 19 Mar 2019
Hello, could you post the right code?
asad jaffar

### asad jaffar (view profile)

on 3 Apr 2019
bro do you have the code?
i am using movsum and then max but what about index? how to find the index
Mohd Sharique Khan

### Mohd Sharique Khan (view profile)

on 29 Jun 2019
function [summa ,index] = max_sum(V,n)
[q a] = size(V);
count = 0;
summa = 0;
if(n>a)
index = -1;
else
for ii = 1:a
if((ii+n-1)>a)
else
k = 0;
for jj = 0:(n-1)
k = k + V(ii+jj);
end
if(summa<k || count==0)
count =1;
summa = k;
index = ii;
end
end
end
end

Sign in to comment.

## 4 Answers

Answer by Guillaume

### Guillaume (view profile)

on 13 Feb 2019
Accepted Answer

Don't use the question title to post the content of your assignment as that get truncated.
Assuming that your assigment is to find the sequence of length n of consecutive numbers with the highest sum, then I don't see how your algorithm even attempts that. You don't care about the maximum of the vector, it's completely irrevelant to the sequence sum. You want to calculate a sliding sum (i.e. first sum(v(1:n)), then sum(v(2:n+1)), etc. and find the maximum of these.
If you're allowed to use movsum, it can be trivially done in just two lines.

Walter Roberson

### Walter Roberson (view profile)

on 4 Apr 2019
There is also an efficient implementation with cumsum(), but that would be better with two lines of code instead of 1.
Maximilian Schmidt

### Maximilian Schmidt (view profile)

on 1 May 2019
@Guillaume: Thank you for your post. I was looking for hints on the same assignment and came across your comment. It seems to be doing the job fine:
h = [6 45 9 67 -36 -34 99 64 67 8]; n = 4;
>> [summa, index] = max(movsum(h, n, 'Endpoints', 'discard'))
summa =
238
index =
7
What I don't understand is how Matlab knows what to do with 'index'. In the documentation for movsum there was no hint about what the funciton returns if you ask for two output arguments. To check that 'index' wasn't some kind of keyword; I tried the above again but used the names 'a' and 'b' instead of summa and index. As I assumed, the output was the same.
So my question: What part of the code tells matlab to output the index of the starting point of the sum in the second output argument?
Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 1 May 2019
@Maximilian Schmidt: movesum is called inside the function max, and it is max is called with two output arguments. So you need to read the max documentation.
A function called inside another function, like movesum inside max in your example, returns exactly one output argument as an input argument to the wrapper function, so
your example:
[summa, index] = max(movsum(h, n, 'Endpoints', 'discard'))
is exactly equivalent to
tmp = movsum(h, n, 'Endpoints', 'discard');
[summa, index] = max(tmp)

Sign in to comment.

Answer by lalit choudhary

### lalit choudhary (view profile)

on 17 Apr 2019

After hours of brainstorming, i finally figured it out
try this code-
function [summa, index]=max_sum(b,n)
y=length(b)
if n>y
summa=0;
index=-1;
else
[summa, index] = max(movsum(b, n, 'Endpoints', 'discard'));
end
end

MANAV MALHOTRA

### MANAV MALHOTRA (view profile)

on 25 Jun 2019
can someone plz explain me what are movsum line is doing and how can we get index???
and also role of endpoints and discard?
plz explain me asap!!!!!
Guillaume

### Guillaume (view profile)

on 25 Jun 2019
Since it's so urgent (why your question is not urgent or an emergency) what's stopping you from looking at the documentation of movsum and have all your questions answered all at once.
Walter Roberson

### Walter Roberson (view profile)

on 25 Jun 2019
%approximate implementation
function r = movsum_with_discard(x, n)
nx = length(x);
r = zeros(1, nx-n+1);
for K = 1 : nx-n+1
r(K) = sum(x(K:K+n-1));
end
end

Sign in to comment.

Answer by asad jaffar

### asad jaffar (view profile)

on 4 Apr 2019

jan and walter take a look at this code this is giving me correct answers except for negative elements array
function [summa, index]=max_sum(b,n)
y=length(b)
q=movsum(b,n)
[maxsum,maxidx]=max(q)
summa=maxsum
index=(maxidx-floor(n/2))
if n==y
j=1
end
end
command window
max_sum([ 79 15 -18 -28 -30 52 -81 31 -74 4 57 -96],4)
y =
12
maxsum=
94 76 48 -61 -24 -87 -28 -72 -120 18 -109 -35
summa =
94
index =
1
index =
1
but i think my code is giving the right value plz take a look and tell me what to do

asad jaffar

### asad jaffar (view profile)

on 4 Apr 2019
i want to say sorry @guillaume the code worked thanks ,and i am sorry i said that your code is wrong ,thanks buddy .can you explain me what does endpoints and discard do how it is working i want to learn .
Jan

### Jan (view profile)

on 5 Apr 2019
@asad: Again: Read the documentation of movsum:
doc movsum
Then try it by your own in the command windows, e.g.:
x = rand(1, 6)
movsum(x, 2)
movsum(x, 2, 'Endpoints', 'discard')
You asked: "are guys even do coursera" - no, of course we do not solve a course for beginners. we have done this about 20 or 30 years ago (a bold but maybe matching guess). We are not going to do exactly what you are doing only to answer very easy programming questions.
"i am waiting" - this is definitely the wrong approach. Exhaustive hints and working code have been posted some hours earlier already.
Some comments to your code:
function [summa, index]=max_sum(b,n)
y=length(b) % This is not useful
q=movsum(b,n)
[maxsum,maxidx]=max(q)
summa=maxsum % Why not directly: [summa,maxidx]=max(q)
index=(maxidx-floor(n/2))
if n==y % While j is not used anywhere, omit this
j=1
end
end
A nicer version:
function [summa, index] = max_sum(b, n)
q = movsum(b, n);
[summa, maxidx] = max(q);
index = maxidx - floor(n / 2);
end
But the result is not correct: The first and last two elements of the sum (or in general: floor(n / 2) elements) are not the sum of n elements of the input vector. See: doc movsum. A solution:
function [summa, index] = max_sum(b, n)
q = movsum(b, n);
m = floor(n / 2);
[summa, index] = max(q(m+1:end-m+1));
end
Try to understand, why q is cropped here. Instead of cropping it is smarter to let movsum exclude the marginal elements already with setting 'Endpoints' to 'discard'.
Vikas Kumar

### Vikas Kumar (view profile)

on 11 Jun 2019
function [summa, index] = max_sum(A,n)
if length(A)<n
summa = 0;
index = -1;
else
B = maxk(A,n)
summa = sum(B);
z = zeros(1,length(B));
m = [];
for i = 1:length(B)
z = find(A==B(i));
m = [m z]
end
T = sort(m)
index = T(1,1)
end
end

Sign in to comment.

Answer by Jaimin Motavar

### Jaimin Motavar (view profile)

on 29 Jun 2019

function [summa,index]=max_sum(a,b)
n=length(a);
summa=0;
total=0;
if b>n
summa=0;
index=-1;
return
end
for i=1:(n-b+1)
for j=i:(b-1+i)
total=total+a(1,j);
end
if total>summa
summa=total;
index=i;
end
total=0;
end
end

Jan

### Jan (view profile)

on 30 Jun 2019
Some simplifications:
function [summa, index] = max_sum(a, b)
n = length(a);
summa = 0;
index = -1;
if b <= n
for i = 1:(n - b + 1)
total = sum(a(i:b - 1 + i));
if total > summa
summa = total;
index = i;
end
end
end
end

Sign in to comment.