runmat_runtime/
matrix.rs

1//! Matrix operations for MATLAB-compatible arithmetic
2//!
3//! Implements element-wise and matrix operations following MATLAB semantics.
4
5use crate::builtins::common::linalg;
6use runmat_builtins::{Tensor, Value};
7use runmat_macros::runtime_builtin;
8
9/// Matrix addition: C = A + B
10pub fn matrix_add(a: &Tensor, b: &Tensor) -> Result<Tensor, String> {
11    if a.rows() != b.rows() || a.cols() != b.cols() {
12        return Err(format!(
13            "Matrix dimensions must agree: {}x{} + {}x{}",
14            a.rows, a.cols, b.rows, b.cols
15        ));
16    }
17
18    let data: Vec<f64> = a
19        .data
20        .iter()
21        .zip(b.data.iter())
22        .map(|(x, y)| x + y)
23        .collect();
24
25    Tensor::new_2d(data, a.rows(), a.cols())
26}
27
28/// Matrix subtraction: C = A - B
29pub fn matrix_sub(a: &Tensor, b: &Tensor) -> Result<Tensor, String> {
30    if a.rows() != b.rows() || a.cols() != b.cols() {
31        return Err(format!(
32            "Matrix dimensions must agree: {}x{} - {}x{}",
33            a.rows, a.cols, b.rows, b.cols
34        ));
35    }
36
37    let data: Vec<f64> = a
38        .data
39        .iter()
40        .zip(b.data.iter())
41        .map(|(x, y)| x - y)
42        .collect();
43
44    Tensor::new_2d(data, a.rows(), a.cols())
45}
46
47/// Matrix multiplication: C = A * B
48pub fn matrix_mul(a: &Tensor, b: &Tensor) -> Result<Tensor, String> {
49    linalg::matmul_real(a, b)
50}
51
52/// GPU-aware matmul entry: if both inputs are GpuTensor handles, call provider; otherwise fall back to CPU.
53pub fn value_matmul(
54    a: &runmat_builtins::Value,
55    b: &runmat_builtins::Value,
56) -> Result<runmat_builtins::Value, String> {
57    crate::builtins::math::linalg::ops::mtimes::mtimes_eval(a, b)
58}
59
60fn complex_matrix_mul(
61    a: &runmat_builtins::ComplexTensor,
62    b: &runmat_builtins::ComplexTensor,
63) -> Result<runmat_builtins::ComplexTensor, String> {
64    linalg::matmul_complex(a, b)
65}
66
67/// Scalar multiplication: C = A * s
68pub fn matrix_scalar_mul(a: &Tensor, scalar: f64) -> Tensor {
69    linalg::scalar_mul_real(a, scalar)
70}
71
72/// Matrix power: C = A^n (for positive integer n)
73/// This computes A * A * ... * A (n times) via repeated multiplication
74pub fn matrix_power(a: &Tensor, n: i32) -> Result<Tensor, String> {
75    if a.rows() != a.cols() {
76        return Err(format!(
77            "Matrix must be square for matrix power: {}x{}",
78            a.rows(),
79            a.cols()
80        ));
81    }
82
83    if n < 0 {
84        return Err("Negative matrix powers not supported yet".to_string());
85    }
86
87    if n == 0 {
88        // A^0 = I (identity matrix)
89        return Ok(matrix_eye(a.rows));
90    }
91
92    if n == 1 {
93        // A^1 = A
94        return Ok(a.clone());
95    }
96
97    // Compute A^n via repeated multiplication
98    // Use binary exponentiation for efficiency
99    let mut result = matrix_eye(a.rows());
100    let mut base = a.clone();
101    let mut exp = n as u32;
102
103    while exp > 0 {
104        if exp % 2 == 1 {
105            result = matrix_mul(&result, &base)?;
106        }
107        base = matrix_mul(&base, &base)?;
108        exp /= 2;
109    }
110
111    Ok(result)
112}
113
114/// Complex matrix power: C = A^n (for positive integer n)
115/// Uses binary exponentiation with complex matrix multiply
116pub fn complex_matrix_power(
117    a: &runmat_builtins::ComplexTensor,
118    n: i32,
119) -> Result<runmat_builtins::ComplexTensor, String> {
120    if a.rows != a.cols {
121        return Err(format!(
122            "Matrix must be square for matrix power: {}x{}",
123            a.rows, a.cols
124        ));
125    }
126    if n < 0 {
127        return Err("Negative matrix powers not supported yet".to_string());
128    }
129    if n == 0 {
130        return Ok(complex_matrix_eye(a.rows));
131    }
132    if n == 1 {
133        return Ok(a.clone());
134    }
135    let mut result = complex_matrix_eye(a.rows);
136    let mut base = a.clone();
137    let mut exp = n as u32;
138    while exp > 0 {
139        if exp % 2 == 1 {
140            result = complex_matrix_mul(&result, &base)?;
141        }
142        base = complex_matrix_mul(&base, &base)?;
143        exp /= 2;
144    }
145    Ok(result)
146}
147
148fn complex_matrix_eye(n: usize) -> runmat_builtins::ComplexTensor {
149    let mut data: Vec<(f64, f64)> = vec![(0.0, 0.0); n * n];
150    for i in 0..n {
151        data[i * n + i] = (1.0, 0.0);
152    }
153    runmat_builtins::ComplexTensor::new_2d(data, n, n).unwrap()
154}
155
156/// Create identity matrix
157pub fn matrix_eye(n: usize) -> Tensor {
158    let mut data = vec![0.0; n * n];
159    for i in 0..n {
160        data[i * n + i] = 1.0;
161    }
162    Tensor::new_2d(data, n, n).unwrap() // Always valid
163}
164
165// Simple built-in function for testing matrix operations
166#[runtime_builtin(name = "matrix_zeros")]
167fn matrix_zeros_builtin(rows: i32, cols: i32) -> Result<Tensor, String> {
168    if rows < 0 || cols < 0 {
169        return Err("Matrix dimensions must be non-negative".to_string());
170    }
171    Ok(Tensor::zeros(vec![rows as usize, cols as usize]))
172}
173
174#[runtime_builtin(name = "matrix_ones")]
175fn matrix_ones_builtin(rows: i32, cols: i32) -> Result<Tensor, String> {
176    if rows < 0 || cols < 0 {
177        return Err("Matrix dimensions must be non-negative".to_string());
178    }
179    Ok(Tensor::ones(vec![rows as usize, cols as usize]))
180}
181
182#[runtime_builtin(name = "matrix_eye")]
183fn matrix_eye_builtin(n: i32) -> Result<Tensor, String> {
184    if n < 0 {
185        return Err("Matrix size must be non-negative".to_string());
186    }
187    Ok(matrix_eye(n as usize))
188}
189
190#[runtime_builtin(name = "matrix_transpose")]
191fn matrix_transpose_builtin(a: Tensor) -> Result<Tensor, String> {
192    let args = [Value::Tensor(a)];
193    let result = crate::call_builtin("transpose", &args)?;
194    match result {
195        Value::Tensor(tensor) => Ok(tensor),
196        other => Err(format!("matrix_transpose: expected tensor, got {other:?}")),
197    }
198}