Skip to main content

nu_command/matrix/
scale.rs

1use crate::matrix::MatrixValue;
2use crate::matrix::value::value_to_f64;
3use nu_engine::command_prelude::*;
4
5#[derive(Clone)]
6pub struct MatrixScale;
7
8impl Command for MatrixScale {
9    fn name(&self) -> &str {
10        "matrix scale"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("matrix scale")
15            .input_output_types(vec![(
16                Type::Custom("matrix".into()),
17                Type::Custom("matrix".into()),
18            )])
19            .required(
20                "scalar",
21                SyntaxShape::Number,
22                "The scalar to multiply each element by.",
23            )
24            .category(Category::Filters)
25    }
26
27    fn description(&self) -> &str {
28        "Multiply all elements of a matrix by a scalar."
29    }
30
31    fn search_terms(&self) -> Vec<&str> {
32        vec!["multiply", "scalar"]
33    }
34
35    fn run(
36        &self,
37        engine_state: &EngineState,
38        stack: &mut Stack,
39        call: &Call,
40        input: PipelineData,
41    ) -> Result<PipelineData, ShellError> {
42        let head = call.head;
43        let scalar: Value = call.req(engine_state, stack, 0)?;
44        let matrix = MatrixValue::from_value(&input.into_value(head)?)?;
45
46        let factor = value_to_f64(&scalar, head).map_err(|_| {
47            ShellError::Generic(nu_protocol::shell_error::generic::GenericError::new(
48                "Invalid argument",
49                "expected a number",
50                head,
51            ))
52        })?;
53
54        let result = matrix.array * factor;
55        Ok(MatrixValue::new(result)
56            .into_value(head)
57            .into_pipeline_data())
58    }
59
60    fn examples(&self) -> Vec<Example<'static>> {
61        vec![
62            Example {
63                description: "Scale a matrix by an integer",
64                example: "matrix identity 2 | matrix scale 3 | matrix into-nu | to nuon",
65                result: Some(Value::test_string("[[3.0, 0.0], [0.0, 3.0]]")),
66            },
67            Example {
68                description: "Scale a matrix by a float",
69                example: "matrix identity 2 | matrix scale 0.5 | matrix into-nu | to nuon",
70                result: Some(Value::test_string("[[0.5, 0.0], [0.0, 0.5]]")),
71            },
72        ]
73    }
74}
75
76#[cfg(test)]
77mod test {
78    use super::*;
79
80    #[test]
81    fn test_examples() -> nu_test_support::Result {
82        nu_test_support::test().examples(MatrixScale)
83    }
84}