0

No matter how I write this script, Powershel will not write my array as it should, it prints a single line array.

PS C:\Windows\system32> $matriz = @(
(1,2,3,4),
(5,6,7,8)
)

Write-Host $matriz
1 2 3 4 5 6 7 8

Neither this way:

PS C:\Windows\system32> $matriz = ,@((1,2,3,4),
(5,6,7,8))

Write-Host $matriz
1 2 3 4 5 6 7 8

How do I print this as a real 2-dimension matrix?
And... I'm trying to populate this same array with Get-Random, but it shows the following error: Failed add the number where you want (i.e. matriz [0,1]) because it doesn't support fractions <- Not the real message but you guys won't understand portuguese :/

*Update:
I want it to be printed as this:
1 2 3 4
5 6 7 8
'Cause the single line thing won't help me to see if my matrix is correct, as a single line I will never know what is in the array's diagonal line.

2
  • What do you want as your desired output? Please Update your question with an example Commented Dec 22, 2014 at 18:13
  • @Matt It didnt worked out, and every tutorial I see the methods that I've posted works just fine... is it possible to be some kind of setting on my powershell? Using PS ISE, the PS "Prompt-Window" outputs as a single line too. Commented Dec 22, 2014 at 18:20

3 Answers 3

2

So when you output an array, powershell by default outputs each array item on a new line. Here is one way to get what I think you want:

Write-Host $matriz | %{$_ -join ' '}

So you tell it to go ahead and use the new line for the outside array, but for each of the inside arrays join them using spaces.

Sign up to request clarification or add additional context in comments.

Comments

0

That is how a two dimensional array prints. If you want to display it in some other way, you'll need to format it yourself:

$matriz  = @((1,2,3,4),(5,6,7,8))

$matriz  | ForEach-Object {
    $_ | ForEach-Object {
        Write-Host ("{0,5}" -f $_) -NoNewline;
    }
    Write-Host;
}

You're also not calling matrix elements correctly. $matriz[1,1], for example, actually means (,$matriz[1] + ,$matriz[1]). That's because 1,1 is itself an array.

What you'd need to do to properly find single elements is to use multiple indexes: $matriz[1][1]

Comments

0

This uses a trick but will make it print in two lines:

$matriz = ,@(1,2,3,4)+,@(5,6,7,8)
$matriz | % {Write-Host $_ }

Output is:

1 2 3 4
5 6 7 8

Each item can be individually referenced as $matriz[x][y] where x,y are the sizes of the two dimentional array (As Bacon said).

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.