Find the first element that satisfy a condition in a vector

조회 수: 10 (최근 30일)
paul mary
paul mary 2019년 3월 19일
답변: Sritama Mitra 2020년 9월 6일
Hello! I have a homework: 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. 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.
for example
  • [summa, index] = max_sum([1 2 3 4 5 4 3 2 1],3)
  • summa = 13
  • index = 4
  • [summa, index] = max_sum([1 2 3 4 5 4 3 2 1],1)
  • summa = 5
  • index = 5
  • [summa, index] = max_sum([1 2 3 4 5 4 3 2 1],9)
  • summa = 25
  • index = 1
Then I have written the code. The summa Part is correct but the index part ist wrong. index is always equal to v(k-n+1). Could someone give me some idea?
Here is the result of my code:
  • max_sum([1 2 3 4 5 4 3 2 1],1)
  • summa =5
  • index =1
function [summa,index] = max_sum(v,n)
k = length(v);
a = zeros(1,k-n+1);
if isscalar(n) == 1 && n > 0 && n == round(n)
if n <= k
for ii = 1:(k-n+1)
b = sum(v(ii:ii+(n-1)));
a(ii) = b;
summa = max(a);
end
index = v(ii);
else
summa = 0;
index = -1;
end
else
fprintf('wrong');
end
  댓글 수: 6
Eva Petrossova
Eva Petrossova 2019년 3월 28일
Hey, I can't manage with it, how did you do ?

댓글을 달려면 로그인하십시오.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 3월 20일
편집: Andrei Bobrov 2019년 3월 20일
function [summa, index] = max_sum(A,n)
B = movsum(A(:),[0 n-1]);
summa = max(B);
index = find(summa == B);
end
or without movsum:
function [summa, index] = max_sum(A,n)
B = A((1:n) + (0:numel(A)-n)');
summa = max(B);
index = find(summa == B);
end
  댓글 수: 1
dpb
dpb 2019년 3월 20일
I'm guessing if OP turns this one in, the instructor eyebrows will raise -- or at least they should! :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sritama Mitra
Sritama Mitra 2020년 9월 6일
function [summa,index]=max_sum(v,n)
k=length(v);
index=ones(1,1);
if n<=k
for i=1:(k-n+1)
b=sum(v(i:i+n-1));
a(i)=b;
summa=max(a);
end
x=find(a==summa);
[o,p]=size(x);
if p~=1
index=x(1);
else
index=x;
end
else
summa=0;
index=-1;
end
end

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by