MATLAB Answers

organize vector, difference between adjacent elements of a vector

2 views (last 30 days)
Fidele Adanvo
Fidele Adanvo on 29 Nov 2020
Commented: Adam Danz on 29 Nov 2020
Hello, everything okay? How can I automate this sequence?
if A=[ a ,b, c ,d ,e, ..........]
outA=[ A(1)-2 , ((A(1)-2)+(A(2)-A(1))) , (((A(1)-2)+(A(2)-A(1))) +(A(3)-A(2))) , ((((A(1)-2)+(A(2)-A(1))) +(A(3)-A(2))) +(A(4)-A(3))), ..............]
for exemple
if A=[ 3 ,10, 55 ,100 ,888, ..........]
outA= [ 3-2, ((3-2)+(10-3)) , ((3-2)+(10-3) +(55-10)), ((3-2)+(10-3) +(55-10)+(100-55)), ((3-2)+(10-3) +(55-10)+(100-55)+(888-100) )]
outA=[ 1 , (1+7), (8+44 ) , (53+44), (98+788)]
outA=[ 1 8 53 98 886]

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 29 Nov 2020
Edited: Adam Danz on 29 Nov 2020
A=[ 3 ,10, 55 ,100 ,888];
z = cumsum(diff([2,A]))
z = 1×5
1 8 53 98 886

  4 Comments

Show 1 older comment
Adam Danz
Adam Danz on 29 Nov 2020
It's doing what you described in your question:
outA=[ A(1)-2 , ((A(1)-2)+(A(2)-A(1))) , (((A(1)-2)+(A(2)-A(1))) +(A(3)-A(2))) , ((((A(1)-2)+(A(2)-A(1))) +(A(3)-A(2))) +(A(4)-A(3))), ...
diff([2,A]) does this: [A(1)-2, A(2)-A(1), A(3)-A(2), A(4)-A(3), ..., A(n+1)-A(n)]
cumsum(__) adds them all together, cumulatively.
Fidele Adanvo
Fidele Adanvo on 29 Nov 2020
How would you please if it were like this?
diff([2,A]) does this: [min(1,(A(1)-2)), A(2)-A(1), A(3)-A(2), A(4)-A(3), ..., A(n+1)-A(n)]
Adam Danz
Adam Danz on 29 Nov 2020
You want to subtract the first element of A by 2 which is why 2 is added to the beginning of [2,A].
If you want to apply the restriction min(1,...) to the first element of A,
z = cumsum(diff([2,A]));
z(1) = min(1,z(1))

Sign in to comment.

More Answers (1)

Ameer Hamza
Ameer Hamza on 29 Nov 2020
Edited: Ameer Hamza on 29 Nov 2020
The rule you described in just A-2
A=[3 ,10, 55 ,100 ,888];
B = A-2;
Result
>> B
B =
1 8 53 98 886
In the sum (A(1)-2) + (A(2)-A(1)) + (A(3)-A(2)) + ... + (A(n)-A(n-1)), after cancelling out the common term, you will only get A(n)-2.

  0 Comments

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!