I'm wondering how to declare a 2D array in bash and then initialize to 0.
In C it looks like this:
int a[4][5] = {0};
And how do I assign a value to an element? As in C:
a[2][3] = 3;
I'm wondering how to declare a 2D array in bash and then initialize to 0.
In C it looks like this:
int a[4][5] = {0};
And how do I assign a value to an element? As in C:
a[2][3] = 3;
Mark Reed suggested a very good solution for 2D arrays (matrix)! They always can be converted in a 1D array (vector). Although Bash doesn't have a native support for 2D arrays, it's not that hard to create a simple ADT around the mentioned principle.
Here is a barebone example with no argument checks, etc, just to keep the solution clear: the array's size is set as two first elements in the instance (documentation for the Bash module that implements a matrix ADT, https://github.com/vorakl/bash-libs/blob/master/src.docs/content/pages/matrix.rst )
Bash doesn't have multi-dimensional array. But you can simulate a somewhat similar effect with associative arrays. The following is an example of associative array pretending to be used as multi-dimensional array:
If you don't declare the array as associative (with
-A
), the above won't work. For example, if you omit thedeclare -A arr
line, theecho
will print2 3
instead of0 1
, because0,0
,1,0
and such will be taken as arithmetic expression and evaluated to0
(the value to the right of the comma operator).You can simulate them for example with hashes, but need care about the leading zeroes and many other things. The next demonstration works, but it is far from optimal solution.
the above example creates a 4x5 matrix with random numbers and print it transposed, with the example result
The principle is: Creating one associative array where the index is an string like
3,4
. The benefits:30,40,2
for 3 dimensional.${matrix[2,3]}
For simulating a 2-dimensional array, I first load the first n-elements (the elements of the first column)
To add the second column, I define the size of the first column and calculate the values in an offset variable
You can also approach this in a much less smarter fashion
of course a 22 line solution or indirection is probably the better way to go and why not sprinkle eval every where to .
Another approach is you can represent each row as a string, i.e. mapping the 2D array into an 1D array. Then, all you need to do is unpack and repack the row's string whenever you make an edit:
Outputs: