Skip to main content

nu_command/matrix/
mean.rs

1use crate::matrix::MatrixValue;
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct MatrixMean;
6
7impl Command for MatrixMean {
8    fn name(&self) -> &str {
9        "matrix mean"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build("matrix mean")
14            .input_output_types(vec![(Type::Custom("matrix".into()), Type::Float)])
15            .category(Category::Filters)
16    }
17
18    fn description(&self) -> &str {
19        "Compute the mean of all elements in a matrix."
20    }
21
22    fn search_terms(&self) -> Vec<&str> {
23        vec!["average", "avg"]
24    }
25
26    fn run(
27        &self,
28        _engine_state: &EngineState,
29        _stack: &mut Stack,
30        call: &Call,
31        input: PipelineData,
32    ) -> Result<PipelineData, ShellError> {
33        let head = call.head;
34        let matrix = MatrixValue::from_value(&input.into_value(head)?)?;
35
36        let count = matrix.array.len() as f64;
37        if count == 0.0 {
38            return Err(ShellError::Generic(
39                nu_protocol::shell_error::generic::GenericError::new(
40                    "Empty matrix",
41                    "cannot compute mean of an empty matrix",
42                    head,
43                ),
44            ));
45        }
46
47        let total: f64 = matrix.array.sum();
48        let mean = total / count;
49
50        Ok(Value::float(mean, head).into_pipeline_data())
51    }
52
53    fn examples(&self) -> Vec<Example<'static>> {
54        vec![
55            Example {
56                description: "Compute the mean of a 2x2 matrix",
57                example: "[[1 2] [3 4]] | into matrix | matrix mean",
58                result: Some(Value::test_float(2.5)),
59            },
60            Example {
61                description: "Compute the mean of an identity matrix",
62                example: "matrix identity 2 | matrix mean",
63                result: Some(Value::test_float(0.5)),
64            },
65        ]
66    }
67}
68
69#[cfg(test)]
70mod test {
71    use super::*;
72
73    #[test]
74    fn test_examples() -> nu_test_support::Result {
75        nu_test_support::test().examples(MatrixMean)
76    }
77}