0
#!/bin/bash
declare -a matrix
num_rows=4
num_columns=5

for ((i=1;i<=num_rows;i++)) do
    for ((j=1;j<=num_columns;j++)) do
        matrix[$i,$j]=$j
    done
done
f1="%$((${#num_rows}+1))s"
f2=" %9s"

printf "$f1" ''
for ((i=1;i<=num_rows;i++)) do
printf "$f2" $i
done
echo

for ((j=1;j<=num_columns;j++)) do
    printf "$f1" $j
    for ((i=1;i<=num_rows;i++)) do
        printf "$f2" ${matrix[$i,$j]}
    done
    echo
done
=> run result:
           1         2         3         4   
 1         1         1         1         1
 2         2         2         2         2
 3         3         3         3         3
 4         4         4         4         4
 5         5         5         5         5

======================== #!/bin/bash declare -a matrix num_rows=4 num_columns=5

for ((i=1;i<=num_rows;i++)) do
    for ((j=1;j<=num_columns;j++)) do
        matrix[$i,$j]=$i
    done
done
f1="%$((${#num_rows}+1))s"
f2=" %9s"

printf "$f1" ''
for ((i=1;i<=num_rows;i++)) do
printf "$f2" $i
done
echo

for ((j=1;j<=num_columns;j++)) do
    printf "$f1" $j
    for ((i=1;i<=num_rows;i++)) do
        printf "$f2" ${matrix[$i,$j]}
    done
    echo
done

if change assignment to the array from $j to $i the result:

           1         2         3         4
 1         4         4         4         4
 2         4         4         4         4
 3         4         4         4         4
 4         4         4         4         4
 5         4         4         4         4

This seems because bash doesn't support multi-dimensional array?

Is there a way to use two dimensional array with bash?

  • Correct, bash doesn't support multi-dimensional arrays. Thus, `${arr[x,y]}` is exactly the same as `${arr[y]}`, as the comma is a math operator that simply evaluates to the value on its right. – Charles Duffy Jul 16 '15 at 23:09
  • http://stackoverflow.com/questions/16487258/how-to-declare-2d-array-in-bash is another dupe; likewise, http://unix.stackexchange.com/questions/109434/attempt-to-fake-a-2d-multidimentional-array-in-bash-by-storing-the-array-name-as – Charles Duffy Jul 16 '15 at 23:11
  • I've had a lot more success with a mixture of bash and gawk. But, if you can, use something like matlab or julia for multi-dimensional arrays. – userABC123 Jul 17 '15 at 03:25

0 Answers0