{"record":{"id":"a0fc44602874d94c","repo":"TheAlgorithms/Python","slug":"the-input-array-is-not-a-square-matrix","errorCode":null,"errorMessage":"The input array is not a square matrix","messagePattern":"The input array is not a square matrix","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"computer_vision/pooling_functions.py","lineNumber":27,"sourceCode":"    \"\"\"\n    This function is used to perform maxpooling on the input array of 2D matrix(image)\n    Args:\n        arr: numpy array\n        size: size of pooling matrix\n        stride: the number of pixels shifts over the input matrix\n    Returns:\n        numpy array of maxpooled matrix\n    Sample Input Output:\n    >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2)\n    array([[ 6.,  8.],\n           [14., 16.]])\n    >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1)\n    array([[241., 180.],\n           [241., 157.]])\n    \"\"\"\n    arr = np.array(arr)\n    if arr.shape[0] != arr.shape[1]:\n        raise ValueError(\"The input array is not a square matrix\")\n    i = 0\n    j = 0\n    mat_i = 0\n    mat_j = 0\n\n    # compute the shape of the output matrix\n    maxpool_shape = (arr.shape[0] - size) // stride + 1\n    # initialize the output matrix with zeros of shape maxpool_shape\n    updated_arr = np.zeros((maxpool_shape, maxpool_shape))\n\n    while i < arr.shape[0]:\n        if i + size > arr.shape[0]:\n            # if the end of the matrix is reached, break\n            break\n        while j < arr.shape[1]:\n            # if the end of the matrix is reached, break\n            if j + size > arr.shape[1]:\n                break","sourceCodeStart":9,"sourceCodeEnd":45,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/computer_vision/pooling_functions.py#L9-L45","documentation":"maxpooling() in computer_vision/pooling_functions.py raises this ValueError when the input array's row count differs from its column count. The pooling loop assumes a square matrix: it computes one edge length for the output and iterates rows/columns symmetrically, so rectangular input would corrupt indices rather than pool correctly.","triggerScenarios":"maxpooling([[1,2,3],[4,5,6]], 2, 2) — a 2x3 list; passing a grayscale-cropped or resized image array whose width != height; passing a numpy array of shape (h, w) with h != w.","commonSituations":"Feeding non-square image crops/patches into a hand-rolled pooling step; assuming the function pads or crops rectangular input like torch.nn.MaxPool2d does; converting RGBA or channel-last arrays without squeezing to a square 2-D grid.","solutions":["Crop or pad the input to square before calling: arr[:n, :n] with n = min(arr.shape)","Or use a library pooling op that supports rectangles: torch.nn.functional.max_pool2d, cv2, or numpy strides","If you own the code, generalize the output shape to ((h-size)//stride+1, (w-size)//stride+1)"],"exampleFix":"# before\nmaxpooling([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], 2, 2)\n# ValueError: The input array is not a square matrix\n\n# after\nimport numpy as np\narr = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])\nn = min(arr.shape)\nmaxpooling(arr[:n, :n], 2, 2)","handlingStrategy":"validation","validationCode":"import numpy as np\narr = np.asarray(arr)\nif arr.ndim != 2 or arr.shape[0] != arr.shape[1]:\n    n = min(arr.shape)\n    arr = arr[:n, :n]  # or pad\nmaxpooling(arr.tolist(), size, stride)","typeGuard":"def is_square(arr) -> bool:\n    a = np.asarray(arr)\n    return a.ndim == 2 and a.shape[0] == a.shape[1]","tryCatchPattern":"try:\n    maxpooling(arr, size, stride)\nexcept ValueError as e:\n    if 'square matrix' in str(e):\n        n = min(np.asarray(arr).shape)\n        return maxpooling(np.asarray(arr)[:n, :n].tolist(), size, stride)\n    raise","preventionTips":["Crop feature maps to square at load time","Prefer torch/cv2 pooling for production pipelines","Add shape assertions in tests: assert arr.shape[0] == arr.shape[1]"],"tags":["computer-vision","pooling","numpy","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}