nu_command/matrix/
identity.rs1use crate::matrix::MatrixValue;
2use crate::matrix::value::positive_dim;
3use ndarray::ArrayD;
4use nu_engine::command_prelude::*;
5
6#[derive(Clone)]
7pub struct MatrixIdentity;
8
9impl Command for MatrixIdentity {
10 fn name(&self) -> &str {
11 "matrix identity"
12 }
13
14 fn signature(&self) -> Signature {
15 Signature::build("matrix identity")
16 .input_output_types(vec![(Type::Nothing, Type::Custom("matrix".into()))])
17 .required(
18 "size",
19 SyntaxShape::Int,
20 "The size of the square identity matrix.",
21 )
22 .category(Category::Filters)
23 }
24
25 fn description(&self) -> &str {
26 "Create an identity matrix of the given size."
27 }
28
29 fn search_terms(&self) -> Vec<&str> {
30 vec!["eye", "unit"]
31 }
32
33 fn run(
34 &self,
35 engine_state: &EngineState,
36 stack: &mut Stack,
37 call: &Call,
38 _input: PipelineData,
39 ) -> Result<PipelineData, ShellError> {
40 let head = call.head;
41 let size = positive_dim(call.req::<i64>(engine_state, stack, 0)?, head)?;
42
43 let mut array = ArrayD::zeros(vec![size, size]);
44 for i in 0..size {
45 array[[i, i]] = 1.0;
46 }
47 Ok(MatrixValue::new(array)
48 .into_value(head)
49 .into_pipeline_data())
50 }
51
52 fn examples(&self) -> Vec<Example<'static>> {
53 vec![
54 Example {
55 description: "Create a 3x3 identity matrix",
56 example: "matrix identity 3 | matrix into-nu | to nuon",
57 result: Some(Value::test_string(
58 "[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]",
59 )),
60 },
61 Example {
62 description: "Create a 2x2 identity matrix",
63 example: "matrix identity 2 | matrix into-nu | to nuon",
64 result: Some(Value::test_string("[[1.0, 0.0], [0.0, 1.0]]")),
65 },
66 ]
67 }
68}
69
70#[cfg(test)]
71mod test {
72 use super::*;
73
74 #[test]
75 fn test_examples() -> nu_test_support::Result {
76 nu_test_support::test().examples(MatrixIdentity)
77 }
78}