How to assign values of a matrix to variables in bash

6,004

As requested, I'm creating a list of variables prefixed with q followed by a sequential number (c) which is then assigned your array variable.

#!/bin/bash
declare -A matrix
num_rows=1
num_columns=50

c=1

for ((n=0;n<=(($num_columns-1));n++)) do
    for ((i=1;i<=num_rows;i++)) do
        matrix[$i,$j]=net$(($n+1))
        declare "q$c=${matrix[$i,$j]}"
        ((c++))
    done
done

To output them, you can use something like:

for ((i=1;i<(($num_columns-1));i++)) do
    var=q$i
    echo "${!var}"
done
Share:
6,004

Related videos on Youtube

zsha
Author by

zsha

Updated on September 18, 2022

Comments

  • zsha
    zsha almost 2 years

    I have created a 50 x 1 matrix in ubuntu as follows:

    #!/bin/bash
    declare -A matrix
    num_rows=1
    num_columns=50
    
    for ((n=0;n<=(($num_columns-1));n++)) do
    for ((i=1;i<=num_rows;i++)) do
        matrix[$i,$j]=net$(($n+1))
        #echo "${matrix[$i,$j]}" >> temp
    done
    done
    

    Now I want to assign each element of the 50 x 1 matrix to a variable (say 'q'); for instance q1=net1, q2=net2,...q50=net50. Does anyone know how to achieve this in linux? Thanks in advance.

    • Jeff Schaller
      Jeff Schaller almost 8 years
      so you want variables that are named according to the lower-case version of the values in the matrix variable, and to be assigned the corresponding upper-case version as a value?
    • Julie Pelletier
      Julie Pelletier almost 8 years
      It's unclear what you're actually trying to do. Are you trying to convert the array to flat assignments or something else? Not sure what would be the point of defining a variable that contains its name.
    • zsha
      zsha almost 8 years
      No I had used those alphabets as example to convey my question. I have edited the question now. Sorry for the confusion!
    • Julie Pelletier
      Julie Pelletier almost 8 years
      If you show us the loop you use to produce your array output, you'll be half-way done. All that would be lacking is a counter and possibly using declare to assign your variables.
    • zsha
      zsha almost 8 years
      I have added my code in the question!
    • Gilles 'SO- stop being evil'
      Gilles 'SO- stop being evil' almost 8 years
      Bash is not a good language for anything more complex than strings and lists of strings. Use a “real” programming language like Python, R, …
  • zsha
    zsha almost 8 years
    Thanks for your suggestion! How do I print the contents of the new matrix "q$c"?
  • Julie Pelletier
    Julie Pelletier almost 8 years
    I just updated my answer to show you a way to do it, but that seems to me like you're getting rid of an array but still want to deal with the result as an array which is counter productive.
  • zsha
    zsha almost 8 years
    Well I don't want my result in the form of an array; I just wanted to be sure that the solution you proposed works :)