When I run the code with any values for a to e and select integration or differentiation my code panics saying that there is a dimension mismatch and I’m not sure why. For reference here is the code I am using
use std::io::{self, Write};
use std::thread;
use std::time::Duration;
use nalgebra::{DMatrix, DVector};
fn main() {
// Initialize polynomial coefficients
let (a, b, c, d, e) = (0.0, 0.0, 0.0, 0.0, 0.0);
let mut _polynomial_vec = DVector::from_row_slice(&[a, b, c, d, e]);
// Derivative matrix
let derivative_mat = DMatrix::from_row_slice(5, 5, &[
0.0, 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 2.0, 0.0, 0.0,
0.0, 0.0, 0.0, 3.0, 0.0,
0.0, 0.0, 0.0, 0.0, 4.0,
0.0, 0.0, 0.0, 0.0, 0.0,
]);
// Integration matrix
let integration_mat = DMatrix::from_row_slice(5, 6, &[
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0 / 3.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.25, 0.0, 0.0,
]);
loop {
println!("Please enter 5 values for the vector:");
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let values: Vec<f64> = input.trim()
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();
if values.len() == 5 {
let (a, b, c, d, e) = (values[0], values[1], values[2], values[3], values[4]);
println!("Your Polynomial is {}x^4 + {}x^3 + {}x^2 + {}x + {}", a, b, c, d, e);
_polynomial_vec = DVector::from_row_slice(&[a, b, c, d, e]);
break;
} else {
println!("Please enter exactly 5 values for the vector.");
}
}
loop{
println!("For Integration please enter I, for Differentiation please enter D");
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let input = input.trim();
match input {
"D" | "d" => {
let derivative_vec = _polynomial_vec * derivative_mat;
println!("The derivative of your polynomial is: {}x^3 + {}x^2 + {}x + {}", derivative_vec[3], derivative_vec[2], derivative_vec[1], derivative_vec[0]);
break;
}
"I" | "i" => {
let extended_vec = _polynomial_vec.insert_row(0, 0.0);
let integral_vec = extended_vec * integration_mat;
println!("The integral of your polynomial is: {}x^5 + {}x^4 + {}x^3 + {}x^2 + {}x + C",
integral_vec[5], integral_vec[4], integral_vec[3], integral_vec[2], integral_vec[1]);
break;
},
_ => continue,
};
};
println!("Closing in 5 seconds...");
thread::sleep(Duration::from_secs(5));
}
I’ve tried to swap the rows and columns of my matrix but I still receive the same error. I’ve also tried swapping the order of the multiplication but then the multiplication gives wrong polynomials for any term except for 1.
hQKirbz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.