Search code examples
powershellmatrixpopulatedynamic-variables

Populate an array using dynamic variables names in Powershell


In this new adventure, I need to populate this matrix fast as i can. So in my mind what i need to do about the variables is:

for ($r = 0 ; $r -lt 5 ; $r++){
    new-variable r$r
    for ($i = 0 ; $i -lt 5 ; $i++){
    $rand = Get-Random -Minimum 0 -Maximum 50
    r$r += "$rand,"
    }
}

But it doesn't work, it tells me that r0 > is not a known cmdlet. This should create r0...r4 variables, wich means row0...row4 and each rn would be filled with a Random number followed by a comma.
How to do it?
And... I really don't know if I'm doing my matrices the right way, but this is what I have now:

$r1 = ""
        for ($i = 0 ; $i -lt 4 ; $i++){
        $rand = Get-Random -Minimum 0 -Maximum 50
        $r1 += "$rand,"
        }
    $r1 = $r1.Replace(" ",",")
    $r1 = $r1.TrimEnd(',')
#    Write-Host $r1

$r2 = ""
        for ($i = 0 ; $i -lt 4 ; $i++){
        $rand = Get-Random -Minimum 0 -Maximum 50
        $r2 += "$rand,"
        }
    $r2 = $r2.Replace(" ",",")
    $r2 = $r2.TrimEnd(',')
#    Write-Host $r2

$matrix = @(($r1),($r2))
foreach ($g in $matrix) {$g}

Solution

  • Just because of your other question I have built this to output the random numbers in the matrix block. It uses $width and $height to define the size of $theMatrix which is built as an array of string arrays.

    $width = 4
    $height = 5
    
    $theMatrix = @()
    For($heightIndex = 1;$heightIndex -le $height;$heightIndex++){
        $theMatrix += ,@(1..$width | ForEach-Object{([string](Get-Random -Minimum 0 -Maximum 50)).PadLeft(2)})
    }
    
    $theMatrix | ForEach-Object{$_ -Join "|"}
    

    This will build a matrix of random numbers. I think this is visually important to you so I converted the numbers to string so that I could use PadLeft when single digits are encountered to make the output look cleaner. In the end use $_ -Join "|" to display the matrix in its readable form. Feel free to change the delimiter to a comma or something else.

    Sample Output

     1|27|23|20
    29|10|25|21
    31|37| 9|27
    11|36|34|48
    43|42|35| 9