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 poss

조회 수: 4 (최근 30일)
I write this code for the qst in desciption
function [summa,index] = max_sum(v,n)
l=length(v);
if n>length(v)
summa =0
index=-1
else
m=v(1:n)
for ii=1:l-n+1
vect=v(ii:ii+n-1)
if sum(m)<sum(vect)
m=vect
end
end
summa = sum(m)
index = m(1)
end
end
and it's working for all exemple in description but for long vector like in qst 2 the result it's false
the problem is the rihjt response it's my, bcz I check it and I don't know if someone can help me if I already didn't undestand the problem

답변 (1개)

Divyam
Divyam 2025년 5월 2일
You can use the 'conv' function to compute the sum of every window of length n efficienty:
function [sum, idx] = max_sum(v, n)
% Finds n consecutive elements in v with the largest sum.
if n > length(v)
error('n must not exceed the length of v');
end
s = conv(v, ones(1, n), 'valid');
% Sliding sum
[sum, idx] = max(s);
end
v = [1 3 2 5 6 2 1];
n = 3;
[sum, idx] = max_sum(v, n)
sum = 13
idx = 3
For more information regarding the 'conv' function, refer to the following documentation: https://www.mathworks.com/help/matlab/ref/conv.html

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by