Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

How do I multiply the corresponding elements in two arrays together?

by Anonymous Monk
on Nov 29, 2000 at 07:23 UTC ( #43830=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

I want to multiply the first terms of the arrays with each other, and the two second terms with each other, etc.

Originally posted as a Categorized Question.

  • Comment on How do I multiply the corresponding elements in two arrays together?

Replies are listed 'Best First'.
Re: How do I multiply the corresponding elements in two arrays together?
by Fang (Pilgrim) on Sep 09, 2005 at 21:00 UTC

    You could use List::MoreUtils:

    use List::MoreUtils qw/pairwise/; @a = (1..5); @b = (6..10); @x = pairwise { $a * $b } @a, @b; print join ", ", @x; __END__ 6, 14, 24, 36, 50

    Be sure to check both array have the same number of elements, or you could get a trail of zeroes:

    use List::MoreUtils qw/pairwise/; @a = (1..5); @b = (6..8); @x = pairwise { $a * $b } @a, @b; print join ", ", @x; __END__ 6, 14, 24, 0, 0
Re: How do I multiply the corresponding elements in two arrays together?
by Russ (Deacon) on Nov 30, 2000 at 00:28 UTC
    I hate to use array indices, but here's one way:
    my @Products = map {$Arr1[$_] * $Arr2[$_]} 0..$#Arr1;
    This assumes that the arrays @Arr1 and @Arr2 exist and are the same length.
Re: Can I multiply corresponding numbers in two arrays together?
by rajib (Novice) on Aug 20, 2002 at 17:47 UTC
    @product; $i = 0; if ($#Arr1 == $#Arr2) { foreach(@Arr1) { $product = $_ * $Arr2[$i]; ++$i; } } else { print "Do you really want to multiply unequal length of arrays?\n"; }

    Originally posted as a Categorized Answer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://43830]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2022-06-27 14:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My most frequent journeys are powered by:









    Results (88 votes). Check out past polls.

    Notices?