Pairwise differences
I wish I'd known MATLAB had... DIFF
- DIFF calculates the sequential differences between numbers in an array.
- It can work on any dimension along the array: Y = DIFF(X,2) calculates differences along the rows.
- For vectors, you can do a diff in different ways - e.g.
Y = DIFF(X) is similar to
Y = [X nan]-[nan X] (except it has an 2 extra columns)
- Warning - DIFF(X) always has one fewer rows (or columns etc. depeding on dimension) than X! I often pad the diff with an extra row:
Y = [ nan(1,size(X,2))
DIFF(X) ]
- Also note that there is a function GRADIENT that does something similar. In particular, the gradient at a point is calculated using the DIFF of the points on either side of it. So,
Y=GRADIENT(X) if X is a vector, is similar to
Y=MEAN([ [nan;GRADIENT(X)], [GRADIENT(X),nan] ])
except at the first and last points (thanks Sean Fallon for this info!).
No comments:
Post a Comment