I believe that the code below modifies $x in place, but I'm not too familiar with the internals of PDL. There is a problem with the code below; for elements equal to 0, it will replace all of those elements with the same result...which may not be what you want.
#!/usr/bin/env perl use strict; use warnings; use PDL; use PDL::NiceSlice; my $x = pdl(0,4,0,-3); print "Before: $x\n"; $x(which($x > 0)) .= 1; $x(which($x < 0)) .= 0; $x(which($x == 0)) .= int(rand(9)) > 5 ? 1: 0; print "After: $x\n"; exit;
The code below will fix that problem, but you need to iterate through each element of the pdl:
#!/usr/bin/env perl use strict; use warnings; use PDL; my $x = pdl(0,4,0,-3); print "Before: $x\n"; my $n = nelem($x); for ( my $i = 0; $i < $n; ++$i ) { my $val = $x->index($i); $val = $val > 0 ? 1 : $val < 0 ? 0 : $val == 0 ? (int(rand(9)) > 5 ? 1 : 0) : undef; $x->index($i) .= $val; } print "After: $x\n"; exit;
By the way, you may find this node helpful: Processing values of a piddle (PDL) speedup using 'at' vs. 'index'. It's a discussion related to processing the elements of a pdl individually. In general, it's a good idea to avoid processing the elements individually (i.e. it's likely better if you can find a way to use the vector operations of PDL). If you can not avoid processing the elements individually, you may want to consider exporting the pdl to a perl array, performing some operations on the values of the array, and then creating a pdl from the result.

I took a quick looked around for the pdl equivalent of the map command but I did not find one.


In reply to Re: PDL, applying function by kevbot
in thread PDL, applying function by rootcho

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.