Skip to content

Commit 632729d

Browse files
author
XuhuaHuang
committed
Upload basic linear algebra example
1 parent 6ab266c commit 632729d

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

src/linalg_basics/Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[package]
2+
name = "linalg_basics"
3+
version = "0.1.0"
4+
edition = "2024"
5+
6+
[dependencies]
7+
nalgebra = "0.33.2"

src/linalg_basics/src/main.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* @file: main.rs
3+
* @brief: This project demonstrates basic linear algebra operations
4+
* @author: Xuhua Huang
5+
* @date: April 18, 2025
6+
* @version: 1.0
7+
*/
8+
use nalgebra::{DMatrix, LU, Vector2, Vector3};
9+
10+
fn main() {
11+
let v = Vector2::new(3.0, 4.0);
12+
let unit_v = v.normalize();
13+
14+
println!("Original: {:?}", v);
15+
println!("Normalized: {:?}", unit_v);
16+
println!("Length of normalized vector: {}", unit_v.norm()); // Will print 1.0
17+
println!("Length of original vector: {}", v.norm()); // Will print 5.0
18+
19+
// Define two 3D vectors
20+
let v1 = Vector3::new(1.0, 2.0, 3.0);
21+
let v2 = Vector3::new(4.0, 5.0, 6.0);
22+
23+
// Vector addition
24+
let sum = v1 + v2;
25+
26+
// Vector subtraction
27+
let diff = v1 - v2;
28+
29+
// Scalar multiplication
30+
let scaled = 2.0 * v1;
31+
32+
// Dot product
33+
let dot = v1.dot(&v2);
34+
35+
// Cross product
36+
let cross = v1.cross(&v2);
37+
38+
// Magnitude (Euclidean norm)
39+
let magnitude = v1.norm();
40+
41+
// Normalization (unit vector)
42+
let normalized = v1.normalize();
43+
44+
// Print results
45+
println!("Sum: {}", sum);
46+
println!("Difference: {}", diff);
47+
println!("Scaled: {}", scaled);
48+
println!("Dot product: {}", dot);
49+
println!("Cross product: {}", cross);
50+
println!("Magnitude: {}", magnitude);
51+
println!("Normalized: {}", normalized);
52+
53+
// Create a dynamic 3x3 matrix
54+
let m = DMatrix::from_row_slice(3, 3, &[2.0, -1.0, 0.0, -1.0, 2.0, -1.0, 0.0, -1.0, 2.0]);
55+
56+
// Perform LU decomposition
57+
let lu = LU::new(m.clone());
58+
59+
// Solve a linear system Ax = b
60+
let b = DMatrix::from_column_slice(3, 1, &[1.0, 0.0, 1.0]);
61+
let x = lu.solve(&b).expect("Matrix is singular");
62+
63+
println!("Solution x:\n{}", x);
64+
65+
// Verify A * x == b
66+
println!("A * x = \n{}", &m * &x);
67+
}

0 commit comments

Comments
 (0)