Issue
At first I declare an array with declare -a matrix and do not initialize any values. Then I print the values of the array in the following way: if a value of the matrix on the particular position equals 1 it should print 1, else it should print _
So without setting any values I get the predictable output.
But if I for example do: matrix[10,10]=1 and I print the array, suddenly always on the position matrix[x,10] the value is always 1.
Why does it behave like this? What do I have to do if I only want to initialize some particular positions with 1 and not all the others in the same row?
#!/bin/bash
#read N
declare -a matrix
for (( i=0; i<10; i++));do
for (( j=0; j<20; j++));do
if [[ matrix[$i,$j] -eq 1 ]];then
printf 1
else
printf _
fi
done
echo
done
echo
matrix[10,10]=1
for (( i=0; i<10; i++));do
for (( j=0; j<20; j++));do
if [[ matrix[$i,$j] -eq 1 ]];then
printf 1
else
printf _
fi
done
echo
done
thats the output:
____________________
____________________
____________________
____________________
____________________
____________________
____________________
____________________
____________________
____________________
__________1_________
__________1_________
__________1_________
__________1_________
__________1_________
__________1_________
__________1_________
__________1_________
__________1_________
__________1_________
Solution
There are no 2D arrays in Bash.
The stuff inside [..]
is arithmetically evaluated. ,
there is a comma operator. The result is the second value. matrix[10,10]=1
is the same as matrix[1,2,3,4,5,etc,10]=1
is the same as matrix[10]=1
.
You can use associative arrays, in which case the stuff inside [...]
is a string, in which case ,
will be a character. declare -A matrix
. Note that your loop (( i=0; i<10; i++))
never goes to 10
.
Answered By - KamilCuk Answer Checked By - Gilberto Lyons (WPSolving Admin)