Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Boolean array indexing

by linuxer (Curate)
on Nov 21, 2013 at 22:16 UTC ( #1063823=note: print w/replies, xml ) Need Help??

in reply to Boolean array indexing

First shot is to let map do the grep's work:

#! /usr/bin/env perl use strict; use warnings; my @a = ( 6,7,8 ); my @b = ( 3,2,1 ); my @c = map { $b[$_] > 1 ? $a[$_] : () } 0 .. $#a; print "@c\n";

Replies are listed 'Best First'.
Re^2: Boolean array indexing
by johnmillerflorida (Initiate) on Nov 21, 2013 at 22:28 UTC

    Thank you very much, linuxer, this is indeed one line :-)

    Still, is there no built-in function in perl which returns the indices of an array based on a boolean query?

    I am moving to perl from matlab (don't want to get into fights about which programming languages are the best (or whether matlab can be considered as one in the first place ;-)), but I think matlab has an edge here, since the equivalent matlab code would be:


      List::MoreUtils has a function indexes which does that:

      indexes BLOCK LIST
      Evaluates BLOCK for each element in LIST (assigned to $_) and returns a list of the indices of those elements for which BLOCK returned a true value. This is just like grep only that it returns indices instead of values:

      @x = indexes { $_ % 2 == 0 } (1..10);   # returns 1, 3, 5, 7, 9

      So you could write

      @a[ indexes { $_ > 1 } @b ]

      Not quite as nice as in Matlab but close.

      matlab is a special purpose tool tuned for handling arrays. Perl is much more a general purpose scripting language. It is unsurprising that there are elegant ways of performing tasks within matlab problem domain that Perl can't directly match. There are many things that Perl does nicely for which matlab has no equivalent. Ya pays ya money (a lot of money in the case of matlab if you're not in an educational institution) and takes ya choice.

      True laziness is hard work

      I had a number of projects in the past where I used Perl to create input files for Matlab, mainly matrices, and then kicked off Matlab to do the processing of those, and then back in Perl created nice reports to present the results (LaTeX files). Using multiple tools (if available) can be very efficient, using each for what it is best for.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1063823]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2021-04-14 09:09 GMT
Find Nodes?
    Voting Booth?

    No recent polls found