Regarding this topic, I've so far found two questions here which relate to my question, but not fully. I have found how to initialize a large array, here. Additionally, I've found how to declare a multi-dimensional array, here. I've yet to find a solution which covers how to both declare AND initialize a multi-dimensional array. In my case, I need an array[10][10] with all elements initialized to zero. Currently I do this as follows:
$array = @(
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
)
This, of course, is completely un-scalable. From the first question, I found that $arr = @(0) * 10000
works for regular arrays, so I tried to use $array = @(@(0) * 10) * 10
, and while this runs just fine, trying to access any element of this array gives me a 'Cannot modify because element is null' error.
To clarify, this code:
$array = @(
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
@(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
)
Write-Host "$($null -eq $array[1][5])"
returns False, where as this code:
$array = @(@(0) * 10) * 10
Write-Host "$($null -eq $array[1][5])"
returns True.
What is the definitive, correct, scalable way to declare and initialize an array with N-dimensions?
CodePudding user response:
What is the definitive, correct, scalable way to declare and initialize an array with N-dimensions?
$2DArray = [int[,]]::new(10,10)
This will create a 10x10 2D array that you can index into like this:
$null -ne $2DArray[1,5]
For a jagged array (an array of arrays), use the unary array operator ,
:
$jaggedArray = ,((0) * 10) * 10
This will create a 10-item array consisting of 10 10-item arrays of 0
that you can index into like this:
$null -ne $jaggedArray[1][5]
As mentioned in the comments, due to PowerShell's tendency to flatten any arrays, it might be better to devise a custom data type for collecting specific information:
using namespace System.Collections.Generic
class SensorSink {
[List[int[]]]$Measurements = [List[int[]]]::new(10)
AcceptTelemetry([int[]]$telemetry){
if($telemetry.Count -ne 10){
throw [ArgumentException]::new('telemetry', "Expected exactly 10 data points, received $($telemetry.Count)")
}
$this.Measurements.Add($telemetry)
}
}