4

The closest I got to was something like

use PDL;
my $u = pdl [1,2,3,4];
my $dim = 4;
for(my $i=0; $i<$dim; $i++)
{
  print $u->flat->index($i), "\n";
}

Also as I can convert [1,2,3,4] to piddle $u, can I get back a list (or a list of lists for a matrix) from $u?

arrac
  • 597
  • 1
  • 5
  • 15

2 Answers2

4

With the wisdom from the monks, I found the answer: http://perlmonks.org/index.pl?node_id=892201

Thought I'd share it here in my original question. The above code can be rewritten as:

use PDL;
my $u = pdl [1,2,3,4];
foreach ($u->dog)
{
  print $_, "\n";
}

The wisdom came with a disclaimer that dog() works only on small piddles (object).

arrac
  • 597
  • 1
  • 5
  • 15
  • There is no limit to what `dog` can work with. I would say that if you are considering looping over a PDL ndarray, you should probably reconsider doing what you're doing in a "vectorised" way. – Ed. Mar 10 '22 at 03:12
4

besides using dog, here are two other options for your 1d pdl using index and list. there is also index2d

use PDL;
my $a = pdl(1 .. 4);
#use index
print $a->index($_), "\n" foreach (0 .. $a->nelem-1);
#use list
print $_ . "\n" foreach ($a->list);
Demian
  • 215
  • 2
  • 9
  • 2
    I would use `$a->at($_)` or `$a->sclr($_)`. The `index` method returns a one-entry PDL object, whereas `at` and `sclr` return a Perl scalar. Furthermore, `sclr` is a bit more forgiving than `at`. – David Mertens Jun 10 '14 at 21:54