Info
This question is locked. Rouvrir pour modifier ou répondre.
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.
71 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
%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
12 commentaires
Vivek Mishra
le 23 Jan 2022
would you please explain the line : total=v(1,1); and total=[total,sum(v(ii):v(jj))];
khalid
le 14 Juil 2023
function [summa,index]=max_sum(v,n)
summa=1;
c=size(v,2);
p=0;
if(n<=c)
for jj=1:(c-n+1)
s=0;
for ii=jj:jj+n-1
s=s+v(1,ii);
end
p = v(1,jj);
if(s>summa)
summa=s;
index=p;
end
end
else
summa = 0;
index =-1;
end
end
Réponse acceptée
KSSV
le 19 Mai 2020
Modifié(e) : KSSV
le 19 Mai 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)
22 commentaires
Walter Roberson
le 6 Août 2021
There is a possibility that there is more than one location that is the maximum. The find() step returns all of the locations and min() of the find returns the first. Another way of doing that would be to use find(Summa==S, 1)
Plus de réponses (23)
Willynx Vixamar
le 13 Nov 2020
function [summa, index] = max_sum(v,n)
L = length(v);
S=zeros(1,L-n+1);
if n > L
summa = 0;
index = -1;
return
else
for i = 1:(L-n+1)
S(i)=sum(v(i:(i+n-1)));
end
summa = max(S);
ind = find(S == summa);
index = min(ind);
end
end
6 commentaires
MINH
le 30 Juin 2023
Can somebody help me explain this part of the code :
ind = find(S == summa);
index = min(ind);
Cheers,
DGM
le 30 Juin 2023
Modifié(e) : DGM
le 30 Juin 2023
The first line returns the linear indices of S where S==summa.
The second line returns the minimum of those indices.
Both lines are unnecessary, because max() will return that index if you actually request it. Why do all this:
summa = max(S);
ind = find(S == summa);
index = min(ind);
... when you can just do:
[summa index] = max(S);
Rik
le 6 Juil 2020
Modifié(e) : Rik
le 30 Juil 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
Bruno Luong
le 29 Juil 2020
Modifié(e) : Bruno Luong
le 29 Juil 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 commentaires
Rik
le 30 Juil 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
le 30 Juil 2020
Modifié(e) : Bruno Luong
le 30 Juil 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.
Bruno Luong
le 1 Août 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 commentaires
tharak infinity
le 10 Nov 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
3 commentaires
OUSSAMA El GABBARI
le 24 Jan 2022
Could you explain the summa = -inf; line ?
Is -inf a built in keyword or something ?
Rik
le 24 Jan 2022
inf is the keyword for infinity. Negative infinity is guaranteed to be the lowest value possible.
Sahil Deshpande
le 17 Déc 2020
function [summa,index] = max_sum(v,n)
l=length(v);m=0;t=0;pointer=1;index=0;
%When n is larger than the length of vector v
if n>l
summa=0;
index=-1;
else
%When n is smaller than the length of vector
for a = 1:n
m=m+v(a);
end
for i = 1:(l-(n-1))
k=i;t=0;
for j = 1:n
t = t+v(k);
k=k+1;
end
if t>m
m=t;
pointer=i;
end
end
summa=m;
index=pointer;
end
I have written this code without using any inbuilt functions, just using loops. It works great!
I know it looks kinda ugly, can anyone help me optimize this code and make it shorter?
1 commentaire
Rik
le 17 Déc 2020
Have you looked at the other solutions in this thread?
Also, you already used a builtin function on your first line: length.
Shantanu Nighot
le 22 Déc 2020
% Here is the working code for This Problem statement
function [summa index] = max_sum(v,n)
ii = 1;
jj = n;
% Initialize summa to zero
summa = 0;
% if n is greater than number of elements in v the return summa = 0, index = -1
if n>numel(v)
summa = 0;
index = -1;
% pro tip
% If n is equal to number of elements in v then index will always be 1 and summa = sum(v(ii:jj))
elseif n==numel(v)
summa = sum(v(ii:jj));
index = 1;
else
% while loop for calculating the sum of n elements of subsequence of v
while jj<=numel(v)
% If sum of n elements of subsequence of v is greater than the previous one
% then that sum is stored in summa and index of first element is stored in index
if sum(v(ii:jj))>summa
summa = sum(v(ii:jj));
index = ii;
end
if sum(v(ii:jj))<0 && summa == 0
summa = sum(v(ii:jj));
index = ii;
end
ii = ii + 1;
jj = jj + 1;
end
end
0 commentaires
Ali Mohammadi
le 21 Oct 2021
and this is my solution for it:
function [summa, index] = max_sum(v, n)
%creat an empty vector for cunsecutive sums, and ultimately determine the
%highest value and its index with max(w)
w = [];
ii = 1;
if n > length(v)
summa = 0
index = -1
return;
else
while n <= length (v)
w(ii) = sum(v(ii:n));
ii = ii + 1;
n = n + 1;
end
[summa, index] = max(w)
end
%I have checked, it works :)
1 commentaire
Eric
le 22 Juil 2020
Modifié(e) : Eric
le 22 Juil 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 commentaires
Eric
le 23 Juil 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
le 29 Juil 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.
Capulus_love
le 11 Août 2020
Modifié(e) : Capulus_love
le 11 Août 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 commentaires
Capulus_love
le 11 Août 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
le 11 Août 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.
LEE MUN LING
le 18 Déc 2020
function [m k]=max_sum(v,n)
m=0;
if n>length(v)
k=-1;
m=0;
return
else
for k=1:((length(v)-n)+1);
while m<max(sum(v(k:((n-1)+k))));
m=max(sum(v(k:((n-1)+k))));
m=m;
k=k;
end
end
end
2 commentaires
LEE MUN LING
le 18 Déc 2020
Can you guys help me check for this,
I try several time inserting the break statement in the loop but the iteration still continues, it is suppose to stop at k=4 when my input argument is ([1 2 3 4 5 4 3 2 1],3)
Rik
le 18 Déc 2020
m=m; and k=k; will not do anything, so why are they in your code? Also, you posted this as an answer, but it is a question. (and you forgot to format your code as code)
Are you aware that break will only stop one loop, not all? And have you looked at the other solutions in this thread?
Rahil Ginwala
le 23 Déc 2020
function [summa, index] = max_sum(v,n)
summa = 0;
i = 0;
j = v;
m = [];
c = 1;
if n>v
summa=0;
index=-1;
else
while i < n
c = numel(v(v==max(j))); % number of times the element is in the array
summa = summa + max(j)*c; % multiplying by c
b = find(v==max(j)); % find the max elemnets of v
m = [m b];% array of positions with max element
j = j(j<max(j));% remove the max number from array
i = i + 1;
end
t = sort(m);
index = t(1,1)
end
% I am not able to stop i from goigng to value 3 which gives the error for sum and index
1 commentaire
Abhishek Sharma
le 28 Jan 2021
% tbh, I used some help from these forum answers too
function [summa,index]=max_sum(v,n)
% first checking whether the size of row vector v is less than n or not
% if yes then print according to the given statement
if n>length(v);
summa=0;
index=-1;
else
% so you are thinking about why i took (-n+1) right?
% think of a value of size of row vector v and n
% you will get to know the answer by yourself ,example take size of v= 10 & n=10
for i=1:(length(v)-n+1);
mysum(i)=sum(v(i:i+n-1));
end
summa=max(mysum);
% I couldn't find this one, hence i used the help of this forum
x=find(mysum==summa);
index=min(x);
end
0 commentaires
Daniel Anaya
le 9 Avr 2021
%i dont know what to do. my works pretty good with positive integers. I dont know wht it has errors with negative integers
function [summa, index] = max_sum(v,n)
summa = 0;
ii = 1;
jj = n;
total = [];
if n > numel(v)
summa = 0;
index = -1;
elseif n == numel(v)
summa = sum(v(ii:jj));
index = v(1,1);
elseif n < numel(v)
for ii = 1:numel(v)
jj = ii + (n - 1);
if jj <= numel(v);
total = [total, sum(v(ii:jj))];
end
end
summa = max(total);
x = find(total == summa);
index2 = min(x);
index = v(index2);
end
3 commentaires
Daniel Anaya
le 9 Avr 2021
Modifié(e) : DGM
le 22 Jan 2023
Thanks for the heads up. I already have the answer. This code works fine now.
function [summa, index] = max_sum(v,n)
summa = 0;
ii = 1;
jj = n;
total = [];
if n > numel(v)
summa = 0;
index = -1;
elseif n == numel(v)
summa = sum(v(ii:jj));
index = 1;
elseif n < numel(v)
for ii = 1:numel(v)
jj = ii + (n - 1);
if jj <= numel(v);
total = [total, sum(v(ii:jj))];
end
end
summa = max(total);
x = find(total == summa);
index = min(x);
end
Shun Yan
le 16 Avr 2021
function [a,b]=max_sum(A,B)
n=1;
C=0;
for ii = 1:(size(A,2)-B+1)
C(n)=sum(A(n:(B+n-1)));
n=n+1;
end
if B>size(A,2)
a=0;
b=-1;
else
a=max(C);
b=find(C==max(C));
end
I don't get what is variable ind, and how's sum 4 index9 wrong; can someone pls help? Thanks!
2 commentaires
Rik
le 16 Avr 2021
What happens when you try this input to your function?
[a,b]=max_sum([1 2 3 4 5 4 3 2 1],2)
Is that correct? How can the index (the second output) be multiple values?
function [a,b]=max_sum(A,B)
n=1;
C=0;
for ii = 1:(size(A,2)-B+1)
C(n)=sum(A(n:(B+n-1)));
n=n+1;
end
if B>size(A,2)
a=0;
b=-1;
else
a=max(C);
b=find(C==max(C));
end
end
Giancarlo milon
le 29 Juin 2021
This is my answer
function [summa,index] = max_sum(v,n)
b=1;
summa = -1000000;
%i start it with -1000000 because you ALWAYS want to overwrite your summa
index = 0;
if n > size(v)
summa = 0;
index = -1;
return
else
%this if checks for size condition if n is bigger than the size summa is 0
%and index -1
while n<=length(v);
%this will break when n = to lenght of the vector
if sum(v(b:n)) > summa
%this condition sets the sumatory of the position from b to n.
%In this case b starts in 1 and n is the input, if the sum is
%bigger than the summa it overwrites it, thats why we wanted
%always to overwrite the value summa and we started it with
%-1000000
summa = sum(v(b:n));
index = b;
end
b = b+1;
n = n+1;
%adds +1 to b and n so my positions go from 1:n to 2:n+1 to 3:n+2
%till n = the lenght and it stops
end
end
3 commentaires
Giancarlo milon
le 23 Juil 2021
the variable double has a max min number, idc wich is it. But u can change the -1000000 for that max min number that the memory can hold in the variable if u want. that should solve it. if ur input is that max min number u can add a counter of times the summa it equal to the starting number, save that position and return that position
Rik
le 23 Juil 2021
Your function should handle such a case. If the user needs to know how your function works and might need to edit your function, then it isn't working well.
Such limitations should be mentioned in the documentation of your function (which it currently lacks).
If you want to overwrite a variable with the lowest possible value, you should replace it with -inf.
%the number you were looking for is this:
-realmax
Ujwal Dhakal
le 6 Jan 2022
function [summa, index] = max_sum(v,n)
a=length(v);
sumvar=zeros(1,a-(n-1)); %preallocating a vector (you can skip this for now_go ahead and read the rest of the code)
%for invalid input
if n>a
summa=0;
index=-1;
return;
end
%assume a matrix on your own and try running i and j using the formula below, you'll get it
for i=1:(a-(n-1))
sumtemp=0;
for j=i:(n+i-1)
sumtemp=sumtemp+v(j);
end
sumvar(i)=sumtemp;%takes the sum and catenates into a vector sumvar _ that was preallocated to save some computational time
end
[summa,index_temp]=max(sumvar(:)); % if you give two output arguments to a max function, the second argument returns index of that element
index=index_temp; % the index of the maximum number in the vector sumvar happens to be also the index of our first number in the sequence
end
0 commentaires
Yifan He
le 27 Juil 2022
function [summa,index] = max_sum(v,n)
if n > length(v)
summa = 0;
index = -1;
end
if n <= length(v)
summa = sum(v(1:n));
index = 1;
for i = 1:length(v)-n
if sum(v(i+1:i+n)) > summa
summa = sum(v(i+1:i+n));
index = i+1;
else
continue;
end
end
end
0 commentaires
Muhammad
le 30 Juil 2022
function [summa,index]=max_sum(v,n)
Z=length(v);
summ=(1:Z-n+1);
if n>Z
summa=0;
index=-1;
return;
else
for i=1:(Z-n+1)
summ(i)=sum(v(i:(i+n-1)));
end
end
[summa,index]=max(summ);
0 commentaires
Nyeche
le 23 Oct 2022
function [summa, index] = max_sum (v, n)
if n < 0 || n ~= fix(n) || ~isrow(v)
error('Input must be an integer');
elseif n > length(v)
summa = 0;
index = -1;
end
total = 0;
l = length(v);
for i = 1:l-(n-1)
total(i) = sum(v(i:i+(n-1)));
summa = max(total);
index_1 = find(total == summa);
index = min(index_1);
end
0 commentaires
Boran Yigit Usta
le 16 Nov 2022
function [summa,index] = max_sum(v, n)
b = zeros(1,n);
a = find(v == max(v));
for ii = 1:n
b(ii) = max(max(v));
if find(v==b(ii),1) < a
a = find(v==b(ii),1);
end
v(find(v==max(v),1)) = 0;
end
if n > length(v)
summa = 0;
index = -1;
else
summa = sum(b);
index = a;
end
1 commentaire
Boran Yigit Usta
le 16 Nov 2022
i tested it it with variety of inputs and it works but still i get this error;
Assessment result: incorrectrandom vectors
Variable summa has an incorrect value. max_sum([ 53 -40 60 -76 -18 31 -61 67 60 75 -60 -2 60 51 -54 -10 -4 -48 -39 80 90 96 53 88 ], 5) returned sum = 429 and index = 10 which is incorrect...
昱安 朱
le 5 Mar 2023
Modifié(e) : DGM
le 5 Mar 2023
function [summa,index]=max_sum(v,n)
len=length(v); %v的長度
if(n>length(v)) %n大於v的長度
summa=0;
index=-1;
return;
else
temp_sum=zeros(1,len-n+1);
for x=1:len-n+1
temp_sum(x)=sum(v(x:x+n-1));
end
[summa,index]=max(temp_sum);
end
end % end of function
1 commentaire
Chaohua
le 3 Juil 2024
function [sumnma,index]=max_sum (v,n)
L = length(v);
summa = zeros(1,L-n+1);%pre-allocation
if n>L
summa = 0;
index = -1;
return
else
for i = 1:(L-n+1) %L-n+1 is the last 'first' element to be considered
summa(i)=sum(v(i:(i+n-1))); %all possible sums
end
[summa,index]=max(summa) %return the max sum and the index
end
0 commentaires
This question is locked.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!