nu_command/matrix/
get_row.rs1use crate::matrix::MatrixValue;
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct MatrixGetRow;
6
7impl Command for MatrixGetRow {
8 fn name(&self) -> &str {
9 "matrix get-row"
10 }
11
12 fn signature(&self) -> Signature {
13 Signature::build("matrix get-row")
14 .input_output_types(vec![(
15 Type::Custom("matrix".into()),
16 Type::List(Box::new(Type::Float)),
17 )])
18 .required(
19 "index",
20 SyntaxShape::Int,
21 "The row index to extract (0-based).",
22 )
23 .category(Category::Filters)
24 }
25
26 fn description(&self) -> &str {
27 "Extract a row from a matrix."
28 }
29
30 fn search_terms(&self) -> Vec<&str> {
31 vec![]
32 }
33
34 fn run(
35 &self,
36 engine_state: &EngineState,
37 stack: &mut Stack,
38 call: &Call,
39 input: PipelineData,
40 ) -> Result<PipelineData, ShellError> {
41 let head = call.head;
42 let index: usize = call.req::<i64>(engine_state, stack, 0)? as usize;
43 let matrix = MatrixValue::from_value(&input.into_value(head)?)?;
44
45 if index >= matrix.array.shape()[0] {
46 return Err(ShellError::Generic(
47 nu_protocol::shell_error::generic::GenericError::new(
48 "Index out of bounds",
49 format!(
50 "row index {} is out of bounds, matrix has {} rows",
51 index,
52 matrix.array.shape()[0]
53 ),
54 head,
55 ),
56 ));
57 }
58
59 let row = matrix.array.index_axis(ndarray::Axis(0), index);
60 let vals: Vec<Value> = row.iter().map(|v| Value::float(*v, head)).collect();
61 Ok(Value::list(vals, head).into_pipeline_data())
62 }
63
64 fn examples(&self) -> Vec<Example<'static>> {
65 vec![
66 Example {
67 description: "Get the first row of a 2x3 matrix",
68 example: "matrix zeros 2 3 | matrix set-row 0 [1.0 2.0 3.0] | matrix get-row 0 | to nuon",
69 result: Some(Value::test_string("[1.0, 2.0, 3.0]")),
70 },
71 Example {
72 description: "Get the second row of a 2x2 identity matrix",
73 example: "matrix identity 2 | matrix get-row 1 | to nuon",
74 result: Some(Value::test_string("[0.0, 1.0]")),
75 },
76 ]
77 }
78}
79
80#[cfg(test)]
81mod test {
82 use super::*;
83
84 #[test]
85 fn test_examples() -> nu_test_support::Result {
86 nu_test_support::test().examples(MatrixGetRow)
87 }
88}