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.
Best Answer