%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=v(1,1);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))]; end [summa,index]=max(total);endend
MATLAB: Write a function max_sum that takes v a row vector of numbers & n,a positive integer as inputs.The function needs to find n consecutive elements of v whose sum is largest possible.It returns summa & index of first element of n consecutive integers.
error locationsoft-lock
Related Question
- Matlab loops/if statements help for a beginner
- 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
- I am trying to write a function that takes both an input vector and scalar (v and n respectively). It needs to output the maximum value of the sum of n consecutive integers of v, as well as the index of the first term in v.
- I have to find the sum of the elements in the upper dimension matrix and this is the code i came up with. When I submitted this code it’s showing error.
- Plz give me a solution
Best Answer