Chethan S.
Chethan S.

Reputation: 556

Difference between adjacent elements - diagonal direction

I have a matrix, I =

 5     4     3
 9     8     6
 6     3     4

How can I calculate differences between adjacent elements in a diagonal directions. I want these outputs(for first and last rows and columns I don't mind padding):

  5     4     3
  5     5     6
  2    -3     4

and

 5     4     3
 9     3     2
 6    -6    -4

Upvotes: 1

Views: 3619

Answers (2)

soandos
soandos

Reputation: 5146

I am not quite sure how to do it syntactically in MATLAB, but in psudocode:

The diagonal adjacent elements for element i,j are at positions:

List of elements = {(i+1,j+1),(i+1,j-1),(i-1,j+1),(i+1,j-1)}.

Basically, for each element position, find its "list of elements" in both matrices, and subtract. Sorry, I can't give you real code.

Upvotes: 0

gnovice
gnovice

Reputation: 125854

You can do this by simple indexing (the following assumes zero padding around the edges as in your example):

>> diagDiffs = I;
>> diagDiffs(2:end,2:end) = I(2:end,2:end)-I(1:end-1,1:end-1)

diagDiffs =

     5     4     3
     9     3     2
     6    -6    -4

>> antidiagDiffs = I;
>> antidiagDiffs(2:end,1:end-1) = I(2:end,1:end-1)-I(1:end-1,2:end)

antidiagDiffs =

     5     4     3
     5     5     6
    -2    -3     4

Upvotes: 1

Related Questions