Hi, this function is to return the maximum value of 'n' consecutive elements but error index exceeds the number of array elements appears for a random applied vector
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi, this function is to return the maximum value of 'n' consecutive elements but error index exceeds the number of array elements appears for a random applied vector
when applied to random vectors:
max_sum([ 26 81 -93 27 -93 74 9 94 80 -95 -99 87 -13 41 6 84 -91 70 84 -4 42 78 ], 12) returned the following MATLAB error: Index exceeds the number of array elements (22).
Here is my function... where am i going wrong? Thank you so much.
function [summa index]=max_sum(v,n)
numb_elements = length(v)
n_elements =[]
if n> (numb_elements)
summa = 0
index = -1
else
summa = -inf
index = 0
for ii= v(1:(numb_elements +1 - n))
n_elements = v(ii:(ii+n-1))
sum_n = sum (v(ii:(ii+ n-1)))
if sum_n > summa
summa = sum_n
index = v(ii)
end
end
end
댓글 수: 0
채택된 답변
Stephen23
2020년 8월 5일
편집: Stephen23
2020년 8월 6일
The main bug is that you are iterating over data values and not indices as your code requires. On this line you define the loop iterator ii to be elements of v, i.e. data values:
for ii= v(1:(numb_elements +1 - n))
but then within your code you use ii as an index. It is trivial to fix by iterating over the indices:
for ii = 1:(numb_elements+1-n)
Your code needs to be much more consistently written, in terms of alignment and spacing. For example the whitespace between operators and numbers, compare:
>> [1 - 2]
ans = -1
>> [1 -2]
ans =
1 -2
>> [1-2]
ans = -1
Sometimes you wrote your code with whitespace around binary operators and sometimes none, which will at some point cause you errors. Solution: write neater, more consistent code. Pick one style and stick with it. Do not mix.
Also align your code consistently:
function [summa index]=max_sum(v,n)
numb_elements = length(v)
if n > (numb_elements)
summa = 0;
index = -1;
else
summa = -inf;
index = 0;
for ii = 1:(numb_elements+1-n)
sum_n = sum(v(ii:(ii+n-1)));
if sum_n > summa
summa = sum_n;
index = v(ii);
end
end
end
Note: I have not checked that this code gives the correct answer (after all, it is your homework), only that it runs without error on the example that you have given.
댓글 수: 2
Stephen23
2020년 8월 6일
@nicola Braham: I hope it helped. You can show your appreciation by accepting my answer :)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!