def matrix_to_images(data_matrix, mask):
    """
    Unmasks rows of a matrix and writes as images

    ANTsR function: `matrixToImages`

    Arguments
    ---------
    data_matrix : numpy.ndarray
        each row corresponds to an image
        array should have number of columns equal to non-zero voxels in the mask

    mask : ANTsImage
        image containing a binary mask. Rows of the matrix are
        unmasked and written as images. The mask defines the output image space

    Returns
    -------
    list of ANTsImage types

    Example
    -------
    >>> import ants
    >>> img = ants.image_read(ants.get_ants_data('r16'))
    >>> msk = ants.get_mask( img )
    >>> img2 = ants.image_read(ants.get_ants_data('r16'))
    >>> img3 = ants.image_read(ants.get_ants_data('r16'))
    >>> mat = ants.image_list_to_matrix([img,img2,img3], msk )
    >>> ilist = ants.matrix_to_images( mat, msk )
    """

    if data_matrix.ndim > 2:
        data_matrix = data_matrix.reshape(data_matrix.shape[0], -1)

    numimages = len(data_matrix)
    numVoxelsInMatrix = data_matrix.shape[1]
    numVoxelsInMask = (mask >= 0.5).sum()
    if numVoxelsInMask != numVoxelsInMatrix:
        raise ValueError(
            "Num masked voxels %i must match data matrix %i"
            % (numVoxelsInMask, numVoxelsInMatrix)
        )

    imagelist = []
    for i in range(numimages):
        img = mask.clone()
        img[mask >= 0.5] = data_matrix[i, :]
        imagelist.append(img)
    return imagelist