필터 지우기
필터 지우기

FOR Loop

조회 수: 5 (최근 30일)
Mayu
Mayu 2011년 12월 12일
편집: DGM 2023년 3월 4일
Let us say I have a row vector with "n" number of rows.
e.g. [0 27 29 45 66]';
How can I write a command using a FOR loop, that adds the first element with the second element, then the second element with the third element and so on until it gets to the "n" number of rows.
And in the end adding up all those answers.
So like: (0+27)+(27+29)+(29+45)... and so on.
I'm only a beginner in MatLab and spent hours trying to figure this out. Hope you guys can help. Thanks for the help in advance. :D

채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 12월 12일
aout = 0;
for i1 = 1:numel(a)-1;
aout = aout + a(i1) + a(i1+1);
end
without loop for..end
n = numel(a)
aout = sum(a(1:n-1)+a(2:n))
  댓글 수: 3
Mayu
Mayu 2011년 12월 12일
Is there a command to just display the last cumulative element.
when i try to display the "aout" it always comes out as the cumulative frequency throughout the whole array.
Sean de Wolski
Sean de Wolski 2011년 12월 12일
aout(end)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Shouvik Das
Shouvik Das 2011년 12월 12일
Considering you need to store each intermediate output in another array. Let input array with n rows be inputArray
outputArray=[];
for i=1:length(inputArray)-1
outputArray(i)=inputArray(i) + inputArray(i+1);
end
Hope this helps.
Regards Shouvik
  댓글 수: 1
Mayu
Mayu 2011년 12월 12일
Thanks, works wonderfully :D

댓글을 달려면 로그인하십시오.


Anurag Pratap Singh
Anurag Pratap Singh 2020년 6월 25일
편집: DGM 2023년 3월 4일
Hi Mayu
You could use an extra array for storing every output let say addArr array and then add each elements of the addArr.
addArr = [];
for i = 1:length(inputArr)
addArr(i) = inputArr(i)+inputArr(i+1);
end
Then add each element of addArr
result = 0;
for i = 1:length(addArr)
result = result+addArr(i);
end
The result variable has the cummulative sum of all the elements in input array.
Thank you

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by