3

I have number of arrays in bash, such as arrKey[], aarT[],P[] and I want to do an arithmetic operation with these arrays. As I checked, arrays are working perfectly but, the arithmetic to find array P[] is wrong. Can anyone help me with this, please?

    #The format is C[0] = (A[0,0]*B[0]) + (A[0,1]*B[1]) 

this is the code that I tried so far.

    P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
    echo ${P[0]}
eddie
  • 1,252
  • 3
  • 15
  • 20
Mohamed Nuzhy
  • 105
  • 1
  • 8
  • 2
    Bash does not support multidimensional arrays. You can simulate it, like check this question for usage : http://stackoverflow.com/questions/16487258/how-to-declare-2d-array-in-bash – Am_I_Helpful Aug 21 '16 at 14:36

1 Answers1

3

There are several issues with your line of code:

P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
  • There is an additional space after the =, erase it.

    P[0]=$(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
    
  • It is incorrect to add two elements outside of an Arithmetic expansion.
    Remove the additional parentheses:

    P[0]=$(({arrKey[0,0]} * {arrT[0]} + {arrKey[0,1]} * {arrT[1]}))
    
  • either use a $ or remove the {…} from variables inside a $(( … )):

    P[0]=$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))
    
  • Even if not strictly required, it is a good idea to quote your expansions:

    P[0]="$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))"
    

Also, make sure that the arrKey has been declared as an associative array:

declare -A arrKey

To make sure the intended double index 0,0 works.