Please find the error

2 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by