in my case, i have an array enveloped in for loop
for i = 1:6
array = [0.5 1 5 2 7 3]
end
now i want to show the result of sum in array element (ex: 0.5 + 1 on first iteration, then 1.5(result of previous iteration) + 5 and so on)
the code that i already try is :
array(i) = array(i) + array(i-1)
but i can't get the result. i already tried with temp, but the problem persists.
thank you

댓글 수: 4

Walter Roberson
Walter Roberson 2019년 3월 21일
Note that each iteration of that "for i" loop, you are overwriting all of array
thanks for the answer!
my first programming language before MATLAB is C#, and apparently C# use recursive for my case (already worked it with my friend).
in C# (for example)
for(int i = 0: i<7; i++)
{
new_array[i] = old_array[i] + old_array[i+1];
}
*it's 7, because c# starts counting from 0
i'm still confused with MATLAB array element, how to express if we want to add array(i) with one element before it(i-1)
What you had before
array(i) = array(i) + array(i-1)
should work, provided i starts at 2.
... But you need to be sure not to overwrite all of array in the loop. The assignment to array should not have been in a loop.
Kenneth Sabandar
Kenneth Sabandar 2019년 3월 21일
thank you! i really appreciate it

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

 채택된 답변

Krishna Kumar
Krishna Kumar 2019년 3월 21일

0 개 추천

Are you just interested in this?
array = [0.5 1 5 2 7 3];
sum=cumsum(array)
If you just want add two neighbouring terms, this should work:
sum= array(1:end-1)+array(2:end)
which basically adds an element with previous one.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 MATLAB Coder에 대해 자세히 알아보기

제품

릴리스

R2017a

태그

Community Treasure Hunt

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

Start Hunting!

Translated by