MATLAB Answers

Write a function max_sum that takes v a row vector of numbers & n,a positive integer as inputs.The function needs to find n consecutive elements of v whose sum is largest possible.It returns summa & index of first element of n consecutive integers.

1,870 views (last 30 days)
vidushi Chaudhary
vidushi Chaudhary on 19 May 2020
Commented: Walter Roberson about 6 hours ago
%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=v(1,1);
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))];
end
[summa,index]=max(total);
end
end

Accepted Answer

KSSV
KSSV on 19 May 2020
Edited: KSSV on 19 May 2020
v = [1 2 3 4 5 4 3 2 1] ;
n = 3 ;
N = length(v) ;
sumn = zeros(1, N - n + 1); % Pre-allocation
for i = 1:N - n + 1
sumn(i) = sum(v(i:(i+n-1))) ;
end
[val,idx] = max(sumn)

  19 Comments

Sign in to comment.

More Answers (13)

Kari Kaala
Kari Kaala on 6 Jul 2020
function [summa, ind] = max_sum(v,n)
% If n is greater than v return the specified values
% Using return keyword exits the function so no further code is
% evaluated
if n > length(v)
summa = 0;
ind = -1;
return;
end
% Initialize summa to -inf.
% Then work through the vector, checking if each sum is larger than the
% current value of summa
summa = -inf;
ind = -1;
% Once we get to length(v)-n+1 we stop moving through the vector
for ii = 1:length(v)-n+1
currentV = v(ii:(ii+n-1));
currentSumma = sum(currentV);
% If currentSumma greater than summa, update summa and ind
if currentSumma > summa
summa = currentSumma;
ind = ii;
end
end
end

  2 Comments

Mikel Jimenez
Mikel Jimenez on 21 Aug 2020 at 11:20
For example, if v = 9 and n= 3, length (v) - n = 6; 6 +1 = 7
ii = 1:7 (at the seventh position it stops moving through the vector, since there are only two elements left in v)

Sign in to comment.


Rik
Rik on 6 Jul 2020
Edited: Rik on 30 Jul 2020
You can get a speedup by using a convolution to calculate the moving sum:
v=randi(100,2000,1);
n=10;
clc
timeit(@() option1(v,n))
timeit(@() option2(v,n))
function [val,idx]=option1(v,n) % function as suggested by KSSV
if n>numel(v),val=0;idx=-1;return,end %my addition
N = length(v) ;
sumn = zeros(1, N - n + 1); % Pre-allocation
for i = 1:(N - n + 1)
sumn(i) = sum(v(i:(i+n-1))) ;
end
[val,idx] = max(sumn);
end
function [val,idx]=option2(v,n)
if n>numel(v),val=0;idx=-1;return,end
sumn=conv(v,ones(n,1),'valid');
[val,idx] = max(sumn);
end

  0 Comments

Sign in to comment.


Bruno Luong
Bruno Luong on 29 Jul 2020
Edited: Bruno Luong on 29 Jul 2020
N=3;
v = [1 2 3 4 5 4 3 2 1];
[s,index] = maxsum(v, N)
Using this function
%% NOTE this function returns empty outputs if N>length(v)
% might be more sensitive to numerical error
function [s,index] = maxsum(v, N);
c=cumsum([0; v(:)]);
[s,index]=max(c(N+1:end)-c(1:end-N));
end
Result
s =
13
index =
4
>>

  4 Comments

Show 1 older comment
Bruno Luong
Bruno Luong on 29 Jul 2020
@Rik: I have not read the timing yet, but not sure I understand the convolution code
v=-ones(5,1)
[val,idx]=option2(v,2)
I get
v =
-1
-1
-1
-1
-1
val =
-1
idx =
5
>>
Is that your intention?
The output val should be -2 as we sum two "-1" regardless where the window is.
I think you should use 'valid' options in CONV and not padding any zero in the kernel. Should workouk carefully to the index of max for N odd/even.
Rik
Rik on 30 Jul 2020
Thanks for the correction. I tested it for random lengths random vectors with random N against your code, and it seems to match now.
The fix doesn't affect the timing.
Bruno Luong
Bruno Luong on 30 Jul 2020
The faster timing of CONV for large array can be perhaps explained by multi-thread of the engine, that cannot be carrierd out with CUMSUM, which is sequential calculation.
TMW comes from far, the CONV in the earlier years suffered from performance. Now they have improved it greatly.
In any case a factor of 0.7 1.5 between two methods are to me essentially ... 1.
In any case your code get a vote from me.

Sign in to comment.


Thyagharajan K K
Thyagharajan K K on 2 Jun 2020
Edited: Rik on 6 Jul 2020
clc;
clear;
A = [1 2 3; 4 5 6; 7 8 9 ; 10 11 12];
summa = halfsum(A)
function summa = halfsum(A)
%This program computes the sum of the elements either
%the sum of the elements above the diagnal if number of columns > rows
%(or) the sum of the elemnts below the diagnal if the number of rows >
%number of columns
%This sum also includes the sum of the elemnts in the diagonal.
summa =0;
[no_of_rows, no_of_cols] = size(A);
min_dim = min(size(A));
if no_of_rows<=no_of_cols
for i = 1:no_of_rows
for j = 1:no_of_cols
if j>=i
summa = summa+ A(i,j);
end
end
end
end
if no_of_rows>no_of_cols
for i = 1:min_dim
for j = 1:min_dim
if i<=j
summa = summa+ A(i,j);
end
end
end
end
end
Edit Rik: moved the documentation for this function from a separately posted answer to here.

  0 Comments

Sign in to comment.


Kari Kaala
Kari Kaala on 6 Jul 2020
function [summa, index] = max_sum(v,n) %function decleration
N = length(v) ; %checking the length of vector v to compare with n
sumx = []; %initiating a null vector to store the sum of consecutive n elements
if n>N %checking if given n is greater than the length of the vector v
summa=0; %if n>N summation is immpossible hence assign summa =0 and index=0 (say)
index=-1;
else %if n<N
for i = 1:N-n+1; %value i runs from 1 to (N+1-n)
sumx = [sumx sum(v(i:(i+n-1)))] ;%storing the summ of n consecutive elements in sumx vector till the condition satisfy
end
[summa,index] = max(sumx); %summa gives the maximum sum of the set in sumx vector and index gives the maximum's index value
end
end

  1 Comment

Rik
Rik on 6 Jul 2020
Your other function is much faster. Why did you decide to post it separately instead of editing this one?

Sign in to comment.


Prince Raj Yadav
Prince Raj Yadav on 21 Jul 2020
max_sum
function [summa, index] = max_sum(v,n)
N = length(v);
B = zeros(1,N-n+1);
if n <= N && n > 0 && n == fix(n)
for i = 1:N-n+1
for j = 1:n
B(i) = B(i) + v(i + j -1);
end
end
summa = max(B);
for ii = 1:length(B)
if B(ii) == summa
break;
end
end
index = ii;
else
summa = 0;
index = -1;
end
end

  0 Comments

Sign in to comment.


Eric
Eric on 22 Jul 2020
Edited: Eric on 22 Jul 2020
I came up with a function that, I think, accomplishes this task. It runs fine in my MATLAB (2020a). However, it doesn't seem to be acceptable in the Assignment Submission. Anyone know why this could be the case?
function[summa,index]=max_sum(v,n)
if n>length(v)
index=-1;
summa=0;
else
sumn=movsum(v,n);
[summa,index]=max(sumn);
index=index-1;
end
end

  5 Comments

Show 2 older comments
Eric
Eric on 23 Jul 2020
Sorry, not logical indexing. That would be "normal" indexing, right? [summa,index]=max(sumn) gives the maximum and index of that (middle) value in the vector sumn. The next line changes that index to the first value in that rolling sum. When running the code with my debugger, it seems to work with a range of values.
TANUJA GUPTA
TANUJA GUPTA on 29 Jul 2020
@Eric, Actually when we type for example [summa,index] = max(sum); it gives the maximum value which is passed to summa, but in index it passes the index of the first no.
[Y,I] = max(X) returns the indices of the maximum values in vector I.
If the values along the first non-singleton dimension contain more
than one maximal element, the index of the first one is returned.

Sign in to comment.


Prahelika Gayatri N
Prahelika Gayatri N on 28 Jul 2020
function [summa,index]= max_sum(v,n)
summa=-inf;
index=-1;
if n>length(v)
summa=0;
index=-1;
return
end
for i=1:length(v)
k=0;
k=k+v(i);
j=1;
while j<n
r=i+j;
if r>length(v)
return
end
k=k+v(r);
j=j+1;
end
if summa<k
summa=k;
index=i;
else
summa=summa;
index=index;
end
end

  0 Comments

Sign in to comment.


Bruno Luong
Bruno Luong on 1 Aug 2020
function [s,index] = maxmovsum(v, N)
c = movsum(v,N);
[s,index] = max(c(1+floor(N/2):end-floor((N-1)/2)));
end

  0 Comments

Sign in to comment.


Capulus_love
Capulus_love on 11 Aug 2020
Edited: Capulus_love on 11 Aug 2020
%why second problem doesn't run?
function [summa,index] = max_sum(v,n)
s = size(v); b = 0; c = 0; index = 0;
if s(2) < n
index = s(2) - n;
summa = 0;
return
end
for i = 1:s(2)-n+1
c = sum(v(i:i+n-1));
if c > b
b = c;
index = i;
else
b = b;
end
end
summa = b;
end
%Variable ind has an incorrect value.
% max_sum([ -66 31 61 60 -70 7 9 0 8 90 -54 72 12 ...
% 89 -50 4 86 -3 83 -52 ], 23) returned sum = 0 and index = -3 which is incorrect...

  3 Comments

Capulus_love
Capulus_love on 11 Aug 2020
in my matlab program,, it returns
summa =0
index = -3
with upper problem.
I'm not sure which part is not solved.
Did I not understand the problem?
Rik
Rik on 11 Aug 2020
Put a breakpoint on the first line. Then use the debugger to execute your function line by line. When do you see the index go negative? When do your variable get unexpected values?
When you do that you will notice that your assumption of a column vector input isn't enforced anywhere.

Sign in to comment.


AKSHAY  K J
AKSHAY K J on 13 Aug 2020
Edited: Rik on 13 Aug 2020
function [summa,index]= max_sum(v,n)
a=0;
if n>length(v)
summa=0;
index=-1;
else
b=-1/0;
for ii=1:length(v)
if(ii+n-1)>length(v)
break;
end
for jj=ii:ii+n-1
a=a+v(jj);
end
if a>b
b=a;
index=ii;
a=0;
else
a=0;
end
end
summa=b;
end
end

  4 Comments

Show 1 older comment
Rik
Rik on 13 Aug 2020
Thanks for posting a complete solution that is equivalent to other solutions in this thread. Especially with the lack of comments I can now hand this is as my homework without bothering to understand the question or the solution.
If you don't edit this answer I will probably delete in somewhere in the next 24 hours.
AKSHAY  K J
AKSHAY K J on 13 Aug 2020
bro i didnt get what should i edit.
I am new to this forum and please help me to get rid of this
are you asking me to include the comments describing the logic involved?
should it be line by line?
Rik
Rik on 13 Aug 2020
You can delete your answer if you want to (and others can do it for you as well). Why did you decide to post it? Answering that question will help in determining what you should edit.
Was your goal to show you can come up with a working solution? Or do you want to teach other users how to solve this question? If it is the latter, you should provide comments in your code explaining why you're doing what you're doing. Explain your thinking so people can understand your code. Currently people can only copy your code. It is not required to write comments, but if you don't, you should make sure the names of your variables are so descriptive you don't need the comments anymore.

Sign in to comment.


SWARNENDU DUTTA
SWARNENDU DUTTA on 13 Aug 2020
function [summa, ind] = max_sum1(v,n)
% If n is greater than v return the specified values
% Using return keyword exits the function so no further code is
% evaluated
if n > length(v)
summa = 0;
ind = -1;
return;
end
% Initialize summa to -inf.
% Then work through the vector, checking if each sum is larger than the
% current value of summa
summa = -inf;
ind = -1;
% Once we get to length(v)-n+1 we stop moving through the vector
for ii = 1:length(v)-n+1
currentV = v(ii:(ii+n-1));
currentSumma = sum(currentV);
% If currentSumma greater than summa, update summa and ind
if currentSumma > summa
summa = currentSumma;
ind = ii;
end
end
end

  0 Comments

Sign in to comment.


lijuan wang
lijuan wang on 30 Aug 2020 at 4:37
Add an answer
function [summa, index] = max_sum(v,n)
m=length(v);
h=[];
if n>m
summa=0
index=-1
else
for i=1:(m-n+1)
k=sum(v(i:(i+n-1)));
h=[h k];
[summa index]=max(h);
end
end
end

  2 Comments

Walter Roberson
Walter Roberson 10 minutes ago
Khaled Bin Easin please make your question more specific. We do not have any idea how much of it you understand, and we do not have time to write two textbooks about computer programming to be sure that we have addressed anything that you might possibly mean by your question.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!