필터 지우기
필터 지우기

Please find the error

조회 수: 3 (최근 30일)
vidushi Chaudhary
vidushi Chaudhary 2020년 5월 19일
답변: Geoff Hayes 2020년 5월 19일
%Write a function called max_sum that takes v as a row vector of numbers, & n,a postive integer as inputs.The function needs to find n consecutive
%elements of v whose sum is the largest possible.If multiple such sequence exists in v,max_sum returns first one.The function returns summa & index
%,the index of first element of n consecutive ones.If n>v,then the function returns summa as 0 & index=-1.
%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=0;
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))]; %Here I'm trying to create a row vector with sum of consecutive n integers
end
end
[summa,index]=max(total);
end
end
  댓글 수: 2
KSSV
KSSV 2020년 5월 19일
Your jj gets equals to 9. Where as your v is of size 1*8. Code tries to extract v(9) so the error.
vidushi Chaudhary
vidushi Chaudhary 2020년 5월 19일
편집: vidushi Chaudhary 2020년 5월 19일
The code is working now,but it's giving incorrect value of summa(It is giving 12 for the above example..).What is wrong?

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

답변 (1개)

Geoff Hayes
Geoff Hayes 2020년 5월 19일
vidushi - the problem is with this line
total=[total,sum(v(ii):v(jj))];
and in particular the inputs to the sum function. Here you are providing two integers (based on the input array) and using the : colon to produce an array of elements between these two. So if your two integers are 1 and 8, then
>> 1:8
ans =
1 2 3 4 5 6 7 8
which is an array of eight integers which isn't what you want. Instead, you want to extract from v a subset or sub-array of consecurtive elements of length 3. So you need to do
total=[total,sum(v(ii:jj))];

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by