# Using GradientFilter[] and GradientOrientationFilter[] to reproduce Matlab's gradient() function

In 'gradient' function in MMA, two methods are given to reproduce Matlab's gradient() function. I thought that GradientFilter[] and GradientOrientationFilter[] could also be used, but half of the orientations are rotated by $$\pi$$ when I tried it:

grad[mat_] := Module[{gradPhi, gradMag, Sx, Sy},
]


Tested with the example from that question:

y = x = Range[-2, 2, 0.2];
z = x Exp[-x^2 - #^2] & /@ y // Transpose;
ListContourPlot[z\[Transpose], PlotRange -> All,
ContourShading -> None, Contours -> 9,
ContourStyle -> ({Thickness[0.005], ColorData["Rainbow"]@#} &) /@
Rescale@Array[# &, 10], InterpolationOrder -> 2,
DataRange -> {{-2, 2}, {-2, 2}}]~Show~
ListVectorPlot[Transpose[pxy, {3, 1, 2}],
DataRange -> {{-2, 2}, {-2, 2}}, VectorColorFunction -> "Rainbow"]

This Attempt Correct

Should this approach work, or am I confusing two different "kinds" of gradients/gradient functions?

• According to the documentation, GradientOrientationFilter returns the angle of a vector parallel to the gradient, which means it may be off by $\pi$. In fact, the documentation states that the angle will be in $(-\pi/2,\pi/2]$. (Side note: the filter functions should accept the matrices themselves, removing the need for the conversion to an image) Jun 25, 2022 at 23:22
• @LukasLang Hm right, I guess if it's parallel to the gradient, there's no way to know if the gradient is $+\frac{\pi}{2}$ or $-\frac{\pi}{2}$ off of that. That seems like a poor design decision... Jun 26, 2022 at 2:55