Mojo-Numerics-and-Algorithms-group / NuMojo

NuMojo is a library for numerical computing in Mojo 🔥 similar to numpy in Python.
Apache License 2.0
86 stars 15 forks source link

[lib] Improve `iter` and `item` functions #76

Closed forFudan closed 1 month ago

forFudan commented 1 month ago

Improve iter function

The iterate will return the first dimensions instead of scalars.

> var A = nm.NDArray[dtype](3, 3, random=True, order="F")
> print(A)
[[      14      -4      -48     ]
[      97      112     -40     ]
[      -59     -94     66      ]]
2-D array  Shape: [3, 3]  DType: int8

> for i in A:
>     print(i)  # Return rows
[       14      -4      -48     ]
1-D array  Shape: [3]  DType: int8
[       97      112     -40     ]
1-D array  Shape: [3]  DType: int8
[       -59     -94     66      ]
1-D array  Shape: [3]  DType: int8

Improve the item function

Align the behavior of item with numpy.

Return the scalar at the coordinates.

If one index is given, get the i-th item of the array. It first scans over the first row, even if it is a column-major array.

If more than one index is given, the length of the indices must match the number of dimensions of the array.

> for i in range(A.size()):
>    print(A.item(i))  # Return 0-d arrays
c stride Stride: [3, 1]
14
c stride Stride: [3, 1]
-4
c stride Stride: [3, 1]
-48
c stride Stride: [3, 1]
97
c stride Stride: [3, 1]
112
c stride Stride: [3, 1]
-40
c stride Stride: [3, 1]
-59
c stride Stride: [3, 1]
-94
c stride Stride: [3, 1]
66

Remove at function

The at function is replaced with item function.

at function has other behaviors in numpy.