JKay
JKay

Reputation: 113

Matlab diff command with bigger step

The command diff calculates differences between two consecutive elements. Is there any way to calculates differences between two nonconsecutive elements?

For example, with

x = [1,2,3,4,5,6]

is there any command to find

[x(3)-x(1),x(4)-x(2),x(5)-x(3),x(6)-x(4)] = [2,2,2,2]

or

[x(4)-x(1),x(5)-x(2),x(6)-x(3)] = [3,3,3]

And in general, for the case of a matrix? I can write some code for this; I just wonder if there any existing command in Matlab for this?

An example of the matrix case

x = [1,2,3,4;1,3,5,7;2,4,6,8] 

and we want to find

[x(1,3)-x(1,1),x(1,4)-x(1,2);x(2,3)-x(2,1),x(2,4)-x(2,2);x(3,3)-x(3,1),x(3,4)-x(3,2)] = [2,2;4,4;4,4]

Upvotes: 1

Views: 560

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112689

For vectors

I would use convolution with kernel [1 0 ··· 0 -1], where the number of zeros depends on the desired step. This can be done with function conv:

x = [1,2,3,4,5,6]; % data
s = 2; % step
result = conv(x, [1 zeros(1,s-1) -1], 'valid');

gives

result =
     2     2     2     2

For matrices or N-dimensional arrays

The above can be generalized using convn, with a kernel defined as before but oriented along the desired dimension:

x = [1,2,3,4; 1,3,5,7; 2,4,6,8]; % data
s = 2; % step
d = 2; % dimension
result = convn(x, reshape(([1 zeros(1,s-1) -1]), [ones(1,d-1) s+1 1]), 'valid');

gives

result =
     2     2
     4     4
     4     4

Upvotes: 4

HansHirse
HansHirse

Reputation: 18905

I'm not aware of such a function, but you can simply set up a very simple anonymous function

stepDiff = @(x, s) x(:, s:end)-x(:, 1:end-s+1);

Will give outputs like:

x = [1, 2, 3, 4, 5, 6];

>> stepDiff(x, 2)
ans =
   1   1   1   1   1      

>> stepDiff(x, 4)
ans =
   3   3   3

x = [1, 2, 3, 4; 1, 3, 5, 7; 2, 4, 6, 8];

>> stepDiff(x, 3)
ans =
   2   2
   4   4
   4   4

Upvotes: 4

Related Questions