Reputation: 13990
Given:
$column1 = @(1,2,3)
$column2 = @(4,5,6)
How can I combine them into an object $matrix which gets displayed as a matrix with the single arrays as columns:
column1 column2
------- -------
1 4
2 5
3 6
Upvotes: 4
Views: 7083
Reputation: 4454
Here's something I created today. It takes a range of 0 to one of the column lengths, then maps it to a list of hashes. Use the select to turn it into a proper table.
$table = 0..$ColA.Length | % { @{
ColA = $ColA[$_]
ColB = $ColB[$_]
}} | Select ColA, ColB
Using the following variables:
$ColA = @(1, 2, 3)
$ColB = @(4, 5, 6)
Results in
ColB ColA
---- ----
1 4
2 5
3 6
Upvotes: 1
Reputation: 2357
Here is a combination of mjolinor and Frode F. solutions. I ran into some problems using Frode's object construction trick using select-object. For some reason it would output hash values likely representing object references. I only code in PowerShell a few times a year, so I am just providing this in case anyone else finds it useful (perhaps even my future self).
$column1 = @(1,2,3)
$column2 = @(4,5,6,7)
$column3 = @(2,5,5,2,1,3);
$max = (
$column1,
$column2,
$column3 |
Measure-Object -Maximum -Property Count).Maximum;
$i=0
0..$max |
foreach {
new-object psobject -property @{
col1 = $Column1[$i]
col3 = $column3[$i]
col2 = $column2[$i++]
}
} | ft -auto
Upvotes: 0
Reputation: 68341
Little better, maybe:
$column1 = @(1,2,3)
$column2 = @(4,5,6,7)
$i=0
($column1,$column2 | sort length)[1] |
foreach {
new-object psobject -property @{
loess = $Column1[$i]
lowess = $column2[$i++]
}
} | ft -auto
loess lowess
----- ------
1 4
2 5
3 6
7
Upvotes: 1
Reputation: 54971
It seems that all of my solutions today requires calculated properties. Try:
$column1 = @(1,2,3)
$column2 = @(4,5,6)
0..($column1.Length-1) | Select-Object @{n="Id";e={$_}}, @{n="Column1";e={$column1[$_]}}, @{n="Column2";e={$column2[$_]}}
Id Column1 Column2
-- ------- -------
0 1 4
1 2 5
2 3 6
If the lengths of the arrays are not equal, you could use:
$column1 = @(1,2,3)
$column2 = @(4,5,6,1)
$max = ($column1, $column2 | Measure-Object -Maximum -Property Count).Maximum
0..$max | Select-Object @{n="Column1";e={$column1[$_]}}, @{n="Column2";e={$column2[$_]}}
I wasn't sure if you needed the Id
, so I included it in the first sample to show how to include it.
Upvotes: 6
Reputation: 13990
I came up with this.. but it seems too verbose. Anything shorter?
&{
for ($i=0; $i -lt $y.Length; $i++) {
New-Object PSObject -Property @{
y = $y[$i]
loess = $smooth_loess[$i]
lowess = $smooth_lowess[$i]
}
}
} | Format-Table -AutoSize
Upvotes: 0