Search code examples
matlabdifferencesubtraction

Matlab- Subtraction of previous in array plus addition of difference


So if I have a matrix s;

s = [4;5;9;12;3]

and I want to calculate the difference between an entry and it's previous entry plus add the previous difference such that I'll get

s = [ 4 0; 5 1; 9 5; 12 8; 3 -1]

I'm quite new to matlab. I understand a for loop would be required to go through the original matrix


Solution

  • The second column of your result seems to be essentially cumsum(diff(s)). However, that's not "the difference between an entry and its previous entry plus the previous difference"; it's the cumulative sum of differences.

    So, if what you want in the second column is the cumulative sum of differences:

    result = [s [0; cumsum(diff(s))]];