how to add to previous value in matlab

32 views (last 30 days)
Suppose i have a matrix
a=[1 2 3 4 5]
I want to add a number such as 2 to the first number in matrix a. so its like
a1=[3 2 3 4 5]
then i want to do a loop or any other function to keep on adding to the previous value from the second number, so it becomes
a2=[3 5 8 12 17]
what code should i write to make this?

Accepted Answer

Star Strider
Star Strider on 7 Apr 2021
Adding a value to the first element simply requires:
a=[1 2 3 4 5]
a(1) = a(1) + 2
The ‘... then I want ...’ part does not require a loop, however it does require the cumsum function:
a = cumsum(a)
producing collectively:
a =
1 2 3 4 5
a =
3 2 3 4 5
a =
3 5 8 12 17
as requested.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!