Saddle points in a matrix
JavaScript (ES6), 179 bytes

a=&gt;a.map((r,y)=&gt;r.map((v,x)=&gt;t+=x*y/r[x+1]&amp;&amp;a[y+1]?[...(S='12221000')+S].map((n,i)=&gt;p-(p=d=Math.sign(v-a[y+~-n][x+~-S[i+2&amp;7]]))&amp;&amp;d?s&amp;s!=-(s=d)?T=a:T++:0,T=s=p=0)|T&gt;&gt;1==4:0),t=0)|t


Try it online!

How?

We iterate on each cell \$v_{y,x}\$ of each row \$r_y\$ of the input matrix.

We first make sure that we're not located over an edge of the matrix with:

x * y / r[x + 1] &amp;&amp; a[y + 1]


(neither \$x\$ or \$y\$ is \$0\$ and both \$v_{y,x+1}\$ and \$r_{y+1}\$ are defined)

We iterate twice on each neighbor cell and keep track of the number of valid segments in \$T\$. By doing this, each segment is guaranteed to be counted twice, except the first one which may be counted either twice or three times, depending on its starting point in relation to the starting point of the cycle. Either way, we have \$\lfloor{T/2}\rfloor=4\$ for order-2 saddle points, in which case we increment the counter \$t\$.

Example:

If the first segment is aligned with the starting point:

neighbor cells: AAAABCCD --&gt; AAAABCCDAAAABCCD
                             ^   ^^ ^^   ^^ ^  --&gt; T = 8


If it is not aligned:

neighbor cells: AABCCDAA --&gt; AABCCDAAAABCCDAA
                             ^ ^^ ^^   ^^ ^^   --&gt; T = 9


We iterate on neighbor cells by starting with the rightmost one and moving clockwise with:

[...(S = '12221000') + S].map((n, i) =&gt; a[x + ~-n][y + ~-S[i + 2 &amp; 7]])


Try it online!

We store the sign of the difference between the current cell and its current neighbor in \$d\$. We keep track of the previous value of \$d\$ in \$p\$ and the previous sign (for non-zero values) in \$s\$.

The logic to update \$p\$, \$s\$ and \$T\$ reads as follows:

p - (p = d) &amp;&amp; d ? s &amp; s != -(s = d) ? T = a : T++ : 0


In plain English:


Ignore identical consecutive values.
Ignore segments with \$d=0\$.
Increment \$T\$ on valid sign transitions.
Whenever an invalid sign transition is detected, do T = a to force all upcoming operations on \$T\$ to either NaN or \$0\$, thus invalidating the final test.