0

I am looking for a Python function that can implement the functionality of movmin. I have included the Matlab description of movmin below.

M = movmin(A,k) returns an array of local k-point centered minimum values, where each minimum is calculated over a sliding window of length k across neighboring elements of A. When k is odd, the window is centered about the element in the current position. When k is even, the window is centered about the current and previous elements. The window size is automatically truncated at the endpoints when there are not enough elements to fill the window. When the window is truncated, the minimum is taken over only the elements that fill the window. M is the same size as A.

If A is a vector, then movmin operates along the length of the vector.

If A is a multidimensional array, then movmin operates along the first array dimension whose size does not equal 1.

My input is a multi-dimensional array.

Community
  • 1
  • 1
desert_ranger
  • 1,096
  • 3
  • 13
  • 26

2 Answers2

2

Code for movMin vector:

def movMin(datas,k):
result = np.empty_like(datas)
start_pt = 0
end_pt = int(np.ceil(k/2))

for i in range(len(datas)):
    if i < int(np.ceil(k/2)):
        start_pt = 0
    if i > len(datas) - int(np.ceil(k/2)):
        end_pt = len(datas)
    result[i] = np.min(datas[start_pt:end_pt])
    start_pt += 1
    end_pt +=1
return result

Test Case:

a = [15,14,11,14,14,4,3,20,4,1]
movMin(a,4)
array([14, 11, 11, 11,  4,  3,  3,  3,  1,  1])
b = [1,14,11,14,4,11,6,3,20,4,2]
movMin(b,11)
array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2])

Here's the code and a test case for reference.

Zhi Fang
  • 36
  • 3
0

Pandas dataframes offer concise, yet powerful, methods for many different types of moving window calculations (or as Pandas calls it: rolling window). Here is a reproduction of the Moving Minimum of Matrix example from MATLAB's movmin documentation:

import pandas as pd

A = pd.DataFrame([[4, 8, 6], [-1, -2, -3], [-1, 3, 4]])
M = A.rolling(window=3, min_periods=1, center=True, axis=1).min()

print(M)
# Output:
#      0    1    2
# 0  4.0  4.0  6.0
# 1 -2.0 -3.0 -3.0
# 2 -1.0 -1.0  3.0
Xukrao
  • 8,003
  • 5
  • 26
  • 52