qfall_math/rational/mat_q/transpose.rs
1// Copyright © 2023 Marcel Luca Schmidt
2//
3// This file is part of qFALL-math.
4//
5// qFALL-math is free software: you can redistribute it and/or modify it under
6// the terms of the Mozilla Public License Version 2.0 as published by the
7// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
8
9//! This module contains the implementation of the `transpose` function.
10
11use crate::traits::*;
12
13use super::MatQ;
14use flint_sys::fmpq_mat::fmpq_mat_transpose;
15
16impl MatQ {
17 /// Returns the transposed form of the given matrix, i.e. rows get transformed to columns
18 /// and vice versa.
19 ///
20 /// # Examples
21 /// ```
22 /// use qfall_math::rational::MatQ;
23 /// use std::str::FromStr;
24 ///
25 /// let mat = MatQ::from_str("[[1/2, 1],[2, 1/7],[2, 1]]").unwrap();
26 /// let cmp = MatQ::from_str("[[1/2, 2, 2],[1, 1/7, 1]]").unwrap();
27 ///
28 /// assert_eq!(mat.transpose(), cmp);
29 /// ```
30 pub fn transpose(&self) -> Self {
31 let mut out = Self::new(self.get_num_columns(), self.get_num_rows());
32 unsafe { fmpq_mat_transpose(&mut out.matrix, &self.matrix) };
33 out
34 }
35}
36
37#[cfg(test)]
38mod test_transpose {
39 use super::MatQ;
40 use std::str::FromStr;
41
42 /// Checks if a row is correctly converted to a column
43 #[test]
44 fn row_to_column() {
45 let mat = MatQ::from_str("[[1/2],[2],[8/4]]").unwrap();
46 let cmp = MatQ::from_str("[[1/2, 2, 2]]").unwrap();
47
48 assert_eq!(cmp, mat.transpose());
49 }
50
51 /// Checks if a column is correctly converted to a row
52 #[test]
53 fn column_to_row() {
54 let mat = MatQ::from_str("[[1/2, 2, 2]]").unwrap();
55 let cmp = MatQ::from_str("[[1/2],[2],[8/4]]").unwrap();
56
57 assert_eq!(cmp, mat.transpose());
58 }
59
60 /// Checks if large, negative, and zero values are transposed correctly
61 #[test]
62 fn different_entry_values() {
63 let mat = MatQ::from_str(&format!(
64 "[[{}, {}, 1/{}, 1/{}, 0]]",
65 i64::MAX,
66 i64::MIN,
67 i64::MAX,
68 i64::MIN
69 ))
70 .unwrap();
71 let cmp = MatQ::from_str(&format!(
72 "[[{}],[{}],[1/{}],[1/{}],[0]]",
73 i64::MAX,
74 i64::MIN,
75 i64::MAX,
76 i64::MIN
77 ))
78 .unwrap();
79
80 assert_eq!(cmp, mat.transpose());
81 }
82}