Matlab diff(F,var,n) vs Python numpy diff(a, n=1, axis=-1)
<p>I am trying to calculate matlab function in python.</p>

<pre><code>y = diff(x,1,2)
</code></pre>

<p>x is and grayscale image </p>

<p>i tried numpy diff function but i get different answer</p>

<p>please help</p>

<p>There are two problems here.  </p>

<p>First, you swapped the order of arguments in <code>np.diff</code>.  MATLAB and Python use the same argument order.  Python supports named arguments, so it is often better to use the argument name to avoid this sort of problem.</p>

<p>Second, python indexing starts with 0, while MATLAB indexing starts with <code>1</code>.  This applies to axes as well, so MATLAB's axis <code>2</code> is Python's axis <code>1</code>.</p>

<p>So the correct function call in Python is <code>np.diff(fimg, 1, 1)</code>, but <code>np.diff(fimg, axis=1)</code> is better IMO.</p>

<p>MATLAB:</p>

<pre><code>&gt;&gt; a = reshape(1:100, 10, [])'

a =

     1     2     3     4     5     6     7     8     9    10
    11    12    13    14    15    16    17    18    19    20
    21    22    23    24    25    26    27    28    29    30
    31    32    33    34    35    36    37    38    39    40
    41    42    43    44    45    46    47    48    49    50
    51    52    53    54    55    56    57    58    59    60
    61    62    63    64    65    66    67    68    69    70
    71    72    73    74    75    76    77    78    79    80
    81    82    83    84    85    86    87    88    89    90
    91    92    93    94    95    96    97    98    99   100

&gt;&gt; diff(a,1, 2)

ans =

     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
</code></pre>

<p>Python:</p>

<pre><code>&gt;&gt;&gt; a = np.arange(100).reshape(10, -1)
&gt;&gt;&gt; print(a)
[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]
 [20 21 22 23 24 25 26 27 28 29]
 [30 31 32 33 34 35 36 37 38 39]
 [40 41 42 43 44 45 46 47 48 49]
 [50 51 52 53 54 55 56 57 58 59]
 [60 61 62 63 64 65 66 67 68 69]
 [70 71 72 73 74 75 76 77 78 79]
 [80 81 82 83 84 85 86 87 88 89]
 [90 91 92 93 94 95 96 97 98 99]]
&gt;&gt;&gt; print(np.diff(a, axis=1))
[[1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1]]
</code></pre>

python matlab numpy scipy