razshan
razshan

Reputation: 1138

Subtract values within same column of n rows in Matlab

I have one column matrix with n rows. I want difference between row 2 and row 1, then row 3 from row 2, and so on. I should have a new matrix with n-1 rows. I am using Matlab.

    513083
    513386
    513662
    513939
    514213
    514471
    514727
    514979
    515225

I tried this: for x = 1:(numel(maxtab(:,1))-1) difference = maxtab(x+1,1) - maxtab(x,1); end but I don't get the matrix. I want to avoid for loops because they slow down the process. Any suggestions. Im trying to do away with Excel because of its limitations on rows.

Upvotes: 0

Views: 1531

Answers (3)

Shai
Shai

Reputation: 114786

Although diff is your antural choice for this task you may also do it "by hand"

>> difference = maxtab(2:end) - maxtab(1:end-1);

Upvotes: 0

tmpearce
tmpearce

Reputation: 12693

I'm not entirely clear on what you're looking for, but it sounds like diff might do the trick:

 mat = [513083
    513386
    513662
    513939
    514213
    514471
    514727
    514979
    515225];
K>> diff(mat)

ans =

   303
   276
   277
   274
   258
   256
   252
   246

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

Use diff().

Upvotes: 1

Related Questions