Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract values in 2 different arrays in perl?

Tags:

perl

Hi I have two arrays containing 4 columns and I want to subtract the value in column1 of array2 from value in column1 of array1 and value of column2 of array2 from column2 of array1 so on..example:

my @array1=(4.3,0.2,7,2.2,0.2,2.4)
my @array2=(2.2,0.6,5,2.1,1.3,3.2)

so the required output is

2.1 -0.4 2     # [4.3-2.2] [0.2-0.6] [7-5]
0.1 -1.1 -0.8  # [2.2-2.1] [0.2-1.3] [2.4-3.2]

For this the code I used is

my @diff = map {$array1[$_] - $array2[$_]} (0..2);          
print OUT join(' ', @diff), "\n";

and the output I am getting now is

2.1 -0.4 2
2.2 -1.1 3.8

Again the first row is used from array one and not the second row, how can I overcome this problem?

I need output in rows of 3 columns like the way i have shown above so just i had filled in my array in row of 3 values.

like image 794
user831579 Avatar asked Aug 16 '11 14:08

user831579


People also ask

How do you subtract two arrays from each other?

Subtract Two ArraysCreate two arrays, A and B , and subtract the second, B , from the first, A . The elements of B are subtracted from the corresponding elements of A . Use the syntax -C to negate the elements of C .

Can we subtract two arrays in C++?

If you are mentioning the subtraction of the elements that have the same indexes, you have to make sure that the array's size is equal. Then iterate through both arrays and subtract one to another using loop. The thing you want to achieve results in undefined behavior.

Can you subtract arrays in Java?

Java Array Subtract subtractElementwise(int[] a, int[] b)Subtracts the values in the two arrays of integers element-wise.


1 Answers

This will produce the requested output. However, I suspect (based on your comments), that we could produce a better solution if you simply showed your raw input.

use strict;
use warnings;

my @a1 = (4.3,0.2,7,2.2,0.2,2.4);
my @a2 = (2.2,0.6,5,2.1,1.3,3.2);
my @out = map { $a1[$_] - $a2[$_] } 0 .. $#a1;

print "@out[0..2]\n";
print "@out[3..$#a1]\n";
like image 119
TLP Avatar answered Sep 25 '22 11:09

TLP