1

I have the following situation in powershell:

$arrayX = 0..1
$arrayY = 0..10

$array1 = @()
$array2 = @()
for ($i = 0; $i -lt $arrayY.Length; $i++){  
        $array1 += $arrayX[0] + $arrayY[$i]
        $array2 += $arrayX[1] + $arrayY[$i]
}

Both $arrayX and $arrayY can be variable in length. If i extend $arrayX by 1 i'll need to adjust the code to take the third value into account. like this:

$arrayX = 0..2
$arrayY = 0..10

$array1 = @()
$array2 = @()
$array3 = @()
for ($i = 0; $i -lt $arrayY.Length; $i++){  
        $array1 += $arrayX[0] + $arrayY[$i]
        $array2 += $arrayX[1] + $arrayY[$i]
        $array3 += $arrayX[2] + $arrayY[$i]
}

What is the best practice in a situation like this to have this work automatic?

3
  • 1
    Why two arrays? Are you really looking for an associative array (hashtable)? Commented Oct 1, 2018 at 21:10
  • this is a simplified version of the problem to make it understandable. i have a complicated math equation that comes down to this. Commented Oct 1, 2018 at 21:14
  • Why are you using powershell to solve math problems @secondplace? Commented Oct 1, 2018 at 22:01

2 Answers 2

2

First, please consider not using the += operation with arrays: it will hurt performance a lot on larger arrays. Since you know the array size in advance you can allocate all required memory in advance:

$array1 = New-Object object[] $arrayY.Length

(you may want to use more specific type instead of object: int or float/double will work)

Next, instead of assigning each array to a variable, you can instead create array of arrays:

$arrayX = 0..2
$arrayY = 0..10

$resultArrays = New-Object int[][] $arrayX.Length

for ($x = 0; $x -lt $resultArrays.Length; ++$x)
{
    $resultArrays[$x] = New-Object int[] $arrayY.Length
}

for ($y = 0; $y -lt $arrayY.Length; ++$y)
{
    for ($x = 0; $x -lt $arrayX.Length; ++$x)
    {
        $resultArrays[$x][$y] = $arrayX[$x] + $arrayY[$y];
    }
}

for ($x = 0; $x -lt $resultArrays.Length; ++$x)
{
    Write-Output "array $($x): $($resultArrays[$x] -join ' ')"
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'll adapt to your advice to not use += if i know the array length. It works like a charm.
If you don't know the size in advance, use something that is resize friendly. System.Collections.Generic.List[object] should work much better.
0

Is this what you are looking for?

$arrayX = 0..2
$arrayY = 0..10

$arrayX | ForEach-Object {
    $aX = $_
    New-Variable -Name ('array' + $($aX+1)) -Value ($arrayY | ForEach-Object {$_ + $aX}) -Force
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.