Please find the error
1 次查看(过去 30 天)
显示 更早的评论
%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
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.
回答(1 个)
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))];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!