add mat ops
This commit is contained in:
@@ -3,4 +3,8 @@ name = "numbrs"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
# [dependencies]
|
||||
|
||||
|
||||
[workspace.lints.rust]
|
||||
non_snake_case = "allow"
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
mod matOps;
|
||||
mod vecOps;
|
||||
|
||||
use matOps::Matrix;
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
let mut a = Matrix::zeros(2, 2);
|
||||
a.mat[0] = vec![-5f32, -7f32];
|
||||
a.mat[1] = vec![2., 4.];
|
||||
println!("{:?}", getEVals(a));
|
||||
}
|
||||
|
||||
fn test() {
|
||||
let ad = [1, 2, 3];
|
||||
pub fn getEVals(m: Matrix) -> (f32, f32) {
|
||||
let trace = m.trace();
|
||||
let determinant = (m.mat[0][0] * m.mat[1][1]) - (m.mat[0][1] * m.mat[1][0]);
|
||||
let descriminant = trace.powi(2) - (4. * determinant);
|
||||
let x1 = (-trace + (descriminant.powf(0.5))) / 2.0;
|
||||
let x2 = (-trace - (descriminant.powf(0.5))) / 2.0;
|
||||
(x1, x2)
|
||||
}
|
||||
|
||||
67
rust/numbrs/src/matOps.rs
Normal file
67
rust/numbrs/src/matOps.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
pub struct Matrix {
|
||||
pub mat: Vec<Vec<f32>>,
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
}
|
||||
|
||||
pub struct Mat2x2 {
|
||||
mat: [[f32; 2]; 2],
|
||||
}
|
||||
|
||||
pub struct Mat3x3 {
|
||||
mat: [[f32; 3]; 3],
|
||||
}
|
||||
|
||||
impl Matrix {
|
||||
pub fn shape(&self) -> (usize, usize) {
|
||||
(self.rows, self.cols)
|
||||
}
|
||||
|
||||
pub fn checkShape(&self) -> bool {
|
||||
if self.mat.len() != self.rows {
|
||||
return false;
|
||||
}
|
||||
|
||||
for i in 0..self.rows {
|
||||
if self.mat.get(i).unwrap().len() != self.cols {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
pub fn zeros(row: usize, col: usize) -> Self {
|
||||
let mut r = vec![0 as f32; col];
|
||||
let mut rs = vec![r; row];
|
||||
Matrix {
|
||||
mat: rs,
|
||||
rows: row,
|
||||
cols: col,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(row: usize, col: usize) -> Self {
|
||||
return Matrix::zeros(row, col);
|
||||
}
|
||||
|
||||
pub fn getTranspose(&self) -> Self {
|
||||
let mut t = Matrix::new(self.rows, self.cols);
|
||||
for i in 0..self.rows {
|
||||
for j in 0..self.cols {
|
||||
t.mat[i][j] = self.mat[j][i];
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
pub fn isSquare(&self) -> bool {
|
||||
self.rows == self.cols
|
||||
}
|
||||
|
||||
pub fn trace(&self) -> f32 {
|
||||
if self.isSquare() {
|
||||
return (0..self.rows).map(|a| self.mat[a][a]).sum();
|
||||
}
|
||||
0.
|
||||
}
|
||||
}
|
||||
@@ -22,3 +22,7 @@ pub fn dotVecVec(v1: &[f32], v2: &[f32]) -> f32 {
|
||||
pub fn mulScalVec<'a>(s: &'a f32, v1: &'a [f32]) -> Vec<f32> {
|
||||
v1.iter().map(|a| a * s).collect()
|
||||
}
|
||||
|
||||
pub fn checkEqualLenVec(v1: &[f32], v2: &[f32]) -> bool {
|
||||
v1.len() == v2.len()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user