Multiply elements of 2 arrays together into another array

So I need to Write an array processing program using a Linux shell programming language to perform the following.
Load array X of 20 numbers from an input file X.
Load array Y of 20 numbers from an input file Y.
Compute array Z by multiply Xi * Yi then compute the square-root of this computation.

What I have done so far is loading the input file X.txt and Y.txt into array X & Y. I try to compute the multiplication and insert it into array Z but I keep getting a syntax error. This complicates me from moving on to compute the square root of the elements in Z.

#!/bin/bash

oldIFS="$IFS"
IFS=$'\n' X=($(<X.txt))
IFS="$oldIFS"

for each in "${X[@]}"
do
	echo "$each"
done

count=${#X[@]}

oldIFS="$IFS"
IFS=$'\n' Y=($(<Y.txt))
IFS="$oldIFS"

for each in "${Y[@]}"
do
	echo "$each"
done


for ((i=0;i<count;i++));do
	Z[$i]=$("${X[$i]} * ${Y[$i]}")
done

for each in "${Z[@]}"
do
	echo "$each"
done

Hi, try:

Z[$i]=$((${X[$i]} * ${Y[$i]}))

Note also that the double quotes should not be there..

This can also be written as:

Z=$((X * Y))

Which you may find easier to read...

1 Like

Hi sarapham40...

Remember 'bash' has only integer arithmetic and can only go to a maximum and minimum whole number integer values depending on whether the OS is 32bit or 64bit.
Square root is not possible in PURE bash as it does not have the ability of floating point maths.
You do have tools at your disposal to get the square roots, (awk, bc, python, perl and others), and drop the results into variables or redirect to files.

If you use 'ksh' as the shell this has excellent builtin floating point maths so you could create your SQRT() function using Newton's method and then the whole would be a PURE shell script.
Alternatively you could use pseudocode x**(1.0/2.0) as your square root too.

Just hints to help on the way...

Bazza...