DMatrix constructors new_random() and identity() fail to infer type

As above, I want to initialise a large (4096 by 4096) matrix. Ideally I’d want to do so statically, but there’s no documentation on doing so with random f64 so I want to check understanding with DMatrix first, as there are better code snippets.

However, let dm3 DMatrix::new_random(4096, 4096) fails due to failing to infer type. That… makes sense, actually, I want an f64 and haven’t specified one. But it also fails with smaller dimensions like (4,3) it also fails. Finally, I checked the reference example for identity():

let dm3 = DMatrix::identity(4, 3); //this is the the reference example!
  |         ---   ^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `N`

If I do put in a type argument, it’s unexpected:

l let dm3 = DMatrix::new_random::<f64>(4, 3);
  |                                     ^^^ unexpected type argument

So, how do new_random() and identity() work?


The scalar type is a type parameter of the DMatrix<N> type. Therefore it needs to be specified using any of the following ways:

let dm3 = DMatrix::<f64>::new_random(4096, 4096);
let dm3: DMatrix<f64> = DMatrix::new_random(4096, 4096);

The same applies to identity.

Oftentimes you don’t even need to specify this explicitly if the compiler is able to infer it from the way you use dm3 afterwards. But in your case the let binding alone is not enough for the compiler to infer f64 automatically.