'convert PDL scalar to Perl scalar

I have a function that uses PDL. The final step is a dot product so it returns a scalar. However, when I try to print this scalar, it is clearly still a piddle and prints like this on screen:

[
  [ 3 ]
]

I'm wondering how I can convert it back to the regular Perl scalar so that it prints like:

3 

More importantly, what is the consequence if I don't convert and take that piddle on to further arithmetic manipulations in a pure Perl context (that does not involve PDL). Thx!



Solution 1:[1]

Use the sclr method, which converts a single-element PDL matrix with any number of dimensions into a simple Perl scalar

my $dotp = sclr($mata x $matb);

Solution 2:[2]

To answer the second question ("what is the consequence if I don't convert and take that piddle on to further arithmetic manipulations in a pure Perl context (that does not involve PDL)"); there are two major considerations:

  • PDL entities ("ndarrays") have overloaded arithmetic so that any Perl scalars used with them will get promoted, and the results will also be ndarrays. For scalar (single-element) ndarrays this is probably undesirable since PDL operations have a performance hit that isn't worth it for a single element
  • the ndarray shown in the example has one element, but it is 2-dimension (1x1); to be a proper scalar ndarray, you'd do $dotp->squeeze to drop all length-1 dims

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2