counting / maths /matrices /matrix_subtract.py
spagestic's picture
feat: enhance Gradio interfaces for matrix operations with detailed descriptions and examples
a561f92
"""
Subtract two matrices using NumPy.
"""
import numpy as np
from typing import List, Union
import gradio as gr
from maths.matrices.utils import parse_matrix, format_output
Matrix = Union[List[List[float]], np.ndarray]
def matrix_subtract(matrix1: Matrix, matrix2: Matrix) -> np.ndarray:
m1 = np.array(matrix1)
m2 = np.array(matrix2)
if m1.shape != m2.shape:
raise ValueError("Matrices must have the same dimensions for subtraction.")
return np.subtract(m1, m2)
matrix_subtract_interface = gr.Interface(
fn=lambda m1_str, m2_str: format_output(matrix_subtract(parse_matrix(m1_str), parse_matrix(m2_str))),
inputs=[
gr.Textbox(label="Matrix 1 (Minuend)", placeholder="e.g., [[5,6],[7,8]]"),
gr.Textbox(label="Matrix 2 (Subtrahend)", placeholder="e.g., [[1,2],[3,4]]")
],
outputs=gr.Textbox(label="Resulting Matrix"),
title="Matrix Subtraction",
description="Subtracts the second matrix from the first. Both matrices must have the same dimensions. Example: Matrix 1: [[5,6],[7,8]], Matrix 2: [[1,2],[3,4]] => Result: [[4,4],[4,4]]",
examples=[
["[[5,6],[7,8]]", "[[1,2],[3,4]]"],
["5,6;7,8", "1,2;3,4"]
]
)