def rectangle_sums(matrix, queries):
    rows = len(matrix)
    cols = len(matrix[0]) if rows else 0
    prefix = [[0] * (cols + 1) for _ in range(rows + 1)]
    for r in range(rows):
        for c in range(cols):
            prefix[r + 1][c + 1] = (
                matrix[r][c] + prefix[r][c + 1]
                + prefix[r + 1][c] - prefix[r][c]
            )
    output = []
    for r1, c1, r2, c2 in queries:
        total = (prefix[r2][c2] - prefix[r1][c2]
                 - prefix[r2][c1] + prefix[r1][c1])
        output.append(total)
    return output
