nu_command/matrix/
zeros.rs1use crate::matrix::MatrixValue;
2use crate::matrix::value::positive_dim;
3use ndarray::ArrayD;
4use nu_engine::command_prelude::*;
5
6#[derive(Clone)]
7pub struct MatrixZeros;
8
9impl Command for MatrixZeros {
10 fn name(&self) -> &str {
11 "matrix zeros"
12 }
13
14 fn signature(&self) -> Signature {
15 Signature::build("matrix zeros")
16 .input_output_types(vec![(Type::Nothing, Type::Custom("matrix".into()))])
17 .required(
18 "dimensions",
19 SyntaxShape::Int,
20 "The dimensions of the zero matrix (e.g., 3 4 for a 3x4 matrix).",
21 )
22 .rest(
23 "more_dimensions",
24 SyntaxShape::Int,
25 "Additional dimensions for n-dimensional arrays.",
26 )
27 .category(Category::Filters)
28 }
29
30 fn description(&self) -> &str {
31 "Create a matrix filled with zeros."
32 }
33
34 fn search_terms(&self) -> Vec<&str> {
35 vec!["zeroes"]
36 }
37
38 fn run(
39 &self,
40 engine_state: &EngineState,
41 stack: &mut Stack,
42 call: &Call,
43 _input: PipelineData,
44 ) -> Result<PipelineData, ShellError> {
45 let head = call.head;
46 let first_dim: i64 = call.req(engine_state, stack, 0)?;
47 let rest_dims: Vec<Value> = call.rest(engine_state, stack, 1)?;
48
49 let mut shape = vec![positive_dim(first_dim, head)?];
50 for v in rest_dims {
51 let d = v.as_int().map_err(|_| {
52 ShellError::Generic(nu_protocol::shell_error::generic::GenericError::new(
53 "Invalid dimensions",
54 "dimensions must be positive integers",
55 head,
56 ))
57 })?;
58 shape.push(positive_dim(d, head)?);
59 }
60
61 let array = ArrayD::zeros(shape);
62 Ok(MatrixValue::new(array)
63 .into_value(head)
64 .into_pipeline_data())
65 }
66
67 fn examples(&self) -> Vec<Example<'static>> {
68 vec![
69 Example {
70 description: "Create a 3x4 matrix of zeros",
71 example: "matrix zeros 3 4 | matrix into-nu | to nuon",
72 result: Some(Value::test_string(
73 "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]",
74 )),
75 },
76 Example {
77 description: "Create a 2x2 matrix of zeros",
78 example: "matrix zeros 2 2 | matrix into-nu | to nuon",
79 result: Some(Value::test_string("[[0.0, 0.0], [0.0, 0.0]]")),
80 },
81 ]
82 }
83}
84
85#[cfg(test)]
86mod test {
87 use super::*;
88
89 #[test]
90 fn test_examples() -> nu_test_support::Result {
91 nu_test_support::test().examples(MatrixZeros)
92 }
93}