What is rust equivalent of `np.ndarray` in python?

Hi

I was wondering what would be the the rust equivalent of np.ndarray in python. I want to pass the equivalent as a type and so I was wondering what would be the type.

Thanks

1 Like

While you can of course make use of ordinary vectors and arrays for simple cases, you may also be interested in the ndarray crate.

1 Like

Ok thanks. But now im still wondering how do I pass in a type of ndarray?

What do you mean by "pass in a type of ndarray"?

Like if I need to make a hashmap what would be the type I pass in for ndarray if the other is a str.

Do you mean you want to make a HashMap<&str, ndarray::Array>? Are you just looking for the type ndarray::Array?

Yes something like that.

Hi

When I try to create the hashmap I get the following error:

wrong number of type arguments: expected 2, found 0

expected 2 type argumentsrustc(E0107)
main.rs(129, 49): expected 2 type arguments

how do i fix it?

Thanks

To help you fix your code, we should know what is this code.

fn get_size_of_cache_in_MB(cache: HashMap<&str, ndarray::Array>) -> i32 {
    let mut tot_size:i32 = 0;
    for key in cache {
        tot_size += cache[key].nbytes;
    }
    let x = i32::pow(10, 6);
    return tot_size / x;
}

Ok here is my code and the error is the one I posted previously.

Check again docs for ndarray::Array (the link was given before). This type requires two parameters, and to create it you must know which values do you put there and how many dimensions it has.

1 Like

The hashmap is somewhere else. The more important thing I want help is what is the correct way to pass this ndarray type.

And what do we mean by dimensions? How do I specify a dimension parameter?

The closest to numpy's ndarray type would probably be ndarray::ArrayD<f64>.

As you will see by reading the docs for ndarray::Array, however, Array is parameterized by two types:

The Array<A, D> is parameterized by A for the element type and D for the dimensionality.

This is because, unlike numpy, ndarray allows you to statically decide how many dimensions your n-dimensional array has. This allows both you to be statically sure that your array has a certain number of dimensions, and the library to provide a specialized type that just handles the one size (thus is better at doing so than the dynamic one).

I'd suggest reading the book's chapter on generics, ndarray's API docs, and possibly some of ndarray's examples, and see what you can learn yourself from those rather than just asking us.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.