convert PDL scalar to Perl scalar

688 views Asked by At

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!

2

There are 2 answers

0
Borodin On BEST ANSWER

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);
0
Ed. On

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