MATLAB: Matlab loops/if statements help for a beginner

beginnermatlab loops if statements

Hello!I know that my code is totally wrong, but since i do not have a teacher I would like some help, in order to learn to think correctly. I have to do this exercise Write a function called max_sum that takes v, a row vector of numbers, and n, a positive integer as inputs. The function needs to find the n consecutive elements of v whose sum is the largest possible. In other words, if v is [1 2 3 4 5 4 3 2 1] and n is 3, it will find 4 5 and 4 because their sum of 13 is the largest of any 3 consecutive elements of v. If multiple such sequences exist in v, max_sum returns the first one. The function returns summa, the sum as the first output argument and index, the index of the first element of the n consecutive ones as the second output. If the input n is larger than the number of elements of v, the function returns 0 as the sum and -1 as the index.
This is my code.
function [summa,index]=max_sum(v,n)
m=size(v);
if n>m
summa=0;
index=-1;
elseif n<- m
for v1=v(1:n-1:m)
summa=sum(max(v1));
index=v1(1);
end
end

Best Answer

So problem 1 is that size is outputting a vector and not a single value. It outputs both dimensions so for your example m is [1 9] which will not work in the if statements as written. Since you know v is a vector then the easiest change here is to change that line to
m = length(v); % outputs 9, the longest dimension
2) in your elseif you have n<-m which makes no sense. I expect you might have meant n<=m but that is really unnecessary anyways and you can remove that entirely to just be an else statement.
3) I do not know what you are trying to do with
v1=v(1:n-1:m)
but I do not think it will work. I would do it as such:
else
summa = 0;
for v1=1:m-n+1 % v1 will loop through 1 2 3 4 5 6 7 in the example
if summa < sum(v(v1:v1+n-1)) % this will sum the 3 consecutive values and check if it is larger than the previous largest summa
summa = sum(v(v1:v1+n-1)); % save the sum as summa
index=v1:v1+n-1; % save the indices that made it
end
end
end
For index do you want the output to be the actual indices [4 5 6] that the largest values occur or the largest values. If you want the largest values and not the indices simply replace the line with this:
index=v(v1:v1+n-1);