Do you want the Principal or Secondary sum? Or both?
Function DiagonalSums{
[CmdletBinding()]
param (
[Parameter()]
[int[,]]
$matrix,
[Parameter()]
[int]
$n # order of the matrix
)
[int]$principal = 0
[int]$secondary = 0
For ($i = 0; $i -lt $n; $i++) {
$principal += $matrix[$i,$i]
$secondary += $matrix[$i,($n - $i - 1)]
}
[PSCustomObject]@{
Principal = $principal
Secondary = $secondary
}
}
# Driver code
#
# test data
#
# Principal diagonal = 18, Secondary diagonal = 18
#$elements = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8
#$n = 4 # order of the matrix
# Principal diagonal = 16, Secondary diagonal = 20
#$elements = 1,2,3,4,4,3,2,1,7,8,9,6,6,5,4,3
#$n=4 # order of the matrix
# Principal diagonal = 3, Secondary diagonal = 3
$elements = 1,1,1,1,1,1,1,1,1
$n = 3 # order of the matrix
$mat = New-Object "int[,]" $n,$n
# load the matrix
$e = 0
For ($i = 0; $i -lt $n; $i++){
For ($j = 0; $j -lt $n; $j++){
$mat[$i,$j] = $elements[$e]
$e++
}
}
DiagonalSums $mat $n