matlab loops/if statements help for a beginner
이전 댓글 표시
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
댓글 수: 2
Renato SL
2019년 10월 8일
A few things:
- m = size(v); If want you want is the length of the vector, you may want to use m = length(v) instead. Otherwise, keep it, but then on the next operations, use m(2) instead since m contains both width & length of v.
- You may need to recheck the elseif statement. I think what you want is <= (less than or equal to)
- You need a third end, which is for the function.
Marilou
2019년 10월 8일
채택된 답변
추가 답변 (1개)
ERTIZA HOSSAIN SHOPNIL
2020년 8월 19일
function [summa,index]= max_sum(v,n)
m=length(v);
if m<n
summa=0;
index=-1;
else
summa = 0;
for i=1:m-n+1
if summa < sum(v(i:i+n-1))
summa = sum(v(i:i+n-1));
index=i;
end
end
end
end
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!