nu_command/matrix/
transpose.rs1use crate::matrix::MatrixValue;
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct MatrixTranspose;
6
7impl Command for MatrixTranspose {
8 fn name(&self) -> &str {
9 "matrix transpose"
10 }
11
12 fn signature(&self) -> Signature {
13 Signature::build("matrix transpose")
14 .input_output_types(vec![(
15 Type::Custom("matrix".into()),
16 Type::Custom("matrix".into()),
17 )])
18 .category(Category::Filters)
19 }
20
21 fn description(&self) -> &str {
22 "Transpose a matrix (swap rows and columns). For n-dimensional arrays, reverses all axes."
23 }
24
25 fn search_terms(&self) -> Vec<&str> {
26 vec!["swap", "flip"]
27 }
28
29 fn run(
30 &self,
31 _engine_state: &EngineState,
32 _stack: &mut Stack,
33 call: &Call,
34 input: PipelineData,
35 ) -> Result<PipelineData, ShellError> {
36 let head = call.head;
37 let matrix = MatrixValue::from_value(&input.into_value(head)?)?;
38
39 let result = if matrix.array.ndim() == 2 {
40 matrix.array.t().to_owned()
41 } else {
42 let axes: Vec<usize> = (0..matrix.array.ndim()).rev().collect();
43 matrix.array.permuted_axes(ndarray::IxDyn(&axes)).to_owned()
44 };
45
46 Ok(MatrixValue::new(result)
47 .into_value(head)
48 .into_pipeline_data())
49 }
50
51 fn examples(&self) -> Vec<Example<'static>> {
52 vec![
53 Example {
54 description: "Transpose a 2x3 matrix to a 3x2 matrix",
55 example: "[[1 2 3] [4 5 6]] | into matrix | matrix transpose | matrix into-nu | to nuon",
56 result: Some(Value::test_string("[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]")),
57 },
58 Example {
59 description: "Transpose an identity matrix (result is the same)",
60 example: "matrix identity 2 | matrix transpose | matrix into-nu | to nuon",
61 result: Some(Value::test_string("[[1.0, 0.0], [0.0, 1.0]]")),
62 },
63 ]
64 }
65}
66
67#[cfg(test)]
68mod test {
69 use super::*;
70
71 #[test]
72 fn test_examples() -> nu_test_support::Result {
73 nu_test_support::test().examples(MatrixTranspose)
74 }
75}