MATLAB: 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

assignmentindex exceeds elements errormax_sum

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

Best Answer

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.