2

I want to write/make/use a 3D array of [m][n][k] in BASH. From what I understand, BASH does not support array that are not 1D.

Any ideas how to do it?

3 Answers 3

5

Fake multi-dimensionality with a crafted associative array key:

declare -A ary
for i in 1 2 3; do 
    for j in 4 5 6; do 
        for k in 7 8 9; do 
            ary["$i,$j,$k"]=$((i*j*k))
        done
    done
done
for key in "${!ary[@]}"; do printf "%s\t%d\n" "$key" "${ary[$key]}"; done | sort
1,4,7   28
1,4,8   32
1,4,9   36
1,5,7   35
1,5,8   40
1,5,9   45
1,6,7   42
1,6,8   48
1,6,9   54
2,4,7   56
2,4,8   64
2,4,9   72
2,5,7   70
2,5,8   80
2,5,9   90
2,6,7   84
2,6,8   96
2,6,9   108
3,4,7   84
3,4,8   96
3,4,9   108
3,5,7   105
3,5,8   120
3,5,9   135
3,6,7   126
3,6,8   144
3,6,9   162

I used sort because keys of an assoc.array have no inherent order.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use associative arrays if your bash is recent enough:

unset assoc
declare -A assoc
assoc["1.2.3"]=x

But, I'd rather switch to a language that supports multidimensional arrays (e.g. Perl).

1 Comment

Good practice is to unset assoc before using declare because it'll cause an error if assoc is already a non-associative array. (i.e. foo=(1,2,3); declare -A foo causes an error)
1

As in C, you can simulate multidimensional array using an offset.

#! /bin/bash

xmax=100
ymax=150
zmax=80
xymax=$((xmax*ymax))
vol=()

for ((z=0; z<zmax; z++)); do
for ((y=0; y<ymax; y++)); do
for ((x=0; x<xmax; x++)); do
    ((t = z*xymax+y*xmax+x))
    if ((vol[t] == 0)); then
        ((vol[t] = vol[t-xymax] + vol[t-ymax] + vol[t-1]))
    fi
done
done
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.