import torch


def matrix_to_cartesian(batch: torch.Tensor, keep_square: bool = False) -> torch.Tensor:
    """
    Transforms a matrix for a homogeneous transformation back to cartesian
    coordinates.

    Args:
        batch: the batch oif matrices to convert back
        keep_square: if False: returns a NDIM x NDIM+1 matrix to keep the
            translation part
            if True: returns a NDIM x NDIM matrix but looses the translation
            part. defaults to False.

    Returns:
        torch.Tensor: the given matrix in cartesian coordinates

    """
    batch = batch[:, :-1, ...]
    if keep_square:
        batch = batch[..., :-1]

    return batch