Matlab- Subtraction of previous in array plus addition of difference

377 views Asked by At

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

2

There are 2 answers

4
Luis Mendo On BEST ANSWER

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))]];
0
anquegi On

In matlab you have a lot of functions for working directly with matrix, the one that feeds here is diff and cumsum please visit the matlab documentation, and the functions for concatening like horzcat or vertcat int his case manually to get what you need work like this:

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

s =

     4
     5
     9
    12
     3

Get the vector my_cum_diff which is the difference between elements in a vector

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

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

my_cum_diff =

     0
     1
     5
     8
    -1

finally concat the two vectors

final_s=[s my_cum_diff]

final_s =

     4     0
     5     1
     9     5
    12     8
     3    -1