5
$\begingroup$

I'm reading a book on MMA and it has an example

Range @ Range @ 3 that produces {{1}, {1, 2}, {1, 2, 3}}

What if I want to make it as matrix 3 x 3, like so {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}. This is perhaps very simple but most functions that I've learned so far operate on rectangular entities.


Keywords: ragged array rectangular reshape append padleft padright

$\endgroup$
5
$\begingroup$

1. I think a didactical answer with relatively simple and often used functions would be something like:

ls = {{1}, {1, 2}, {1, 2, 3}};

n = 3;
Map[Join[#, Table[0, {n - Length[#]}]] &, ls]

Out[107]= {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}

2. We can also see ls as the nonzero elements in a sparse matrix and program this:

In[103]:= Normal@SparseArray[Position[ls, _Integer] -> Flatten[ls]]

Out[103]= {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}

3. And, of course, we can use the specialized function PadRight. (As mentioned by Kuba in a comment.)

$\endgroup$
  • $\begingroup$ may be also ArrayReshape[#, {n}, 0] & /@ ls; and Table[0, n] seems easier than Table[0, {n}] $\endgroup$ – garej May 5 '17 at 19:37
  • $\begingroup$ @garej Sure. But since the user is a beginner it is better to give instructive solutions than solutions that have to be deciphered. $\endgroup$ – Anton Antonov May 6 '17 at 5:17
11
$\begingroup$

Some very complex answers. Not sure why you wouldn't simply use PadRight which was apparently referenced in a comment that is no longer there.

PadRight[{{1}, {1, 2}, {1, 2, 3}}]

(* {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}} *)
$\endgroup$
  • 1
    $\begingroup$ This is what I think after first glance. :) $\endgroup$ – yode May 6 '17 at 6:24
6
$\begingroup$

In:

(*Method 1*)
Table[Range[3], 3] // LowerTriangularize
Array[#2 &, {3, 3}] // LowerTriangularize
Array[#1 &, {3, 3}] // Transpose // LowerTriangularize
BoxMatrix[1] Range[3] // Transpose // LowerTriangularize
BoxMatrix[1] + Range[0, 2] // Transpose // LowerTriangularize

(*Method 2*)    
DiagonalMatrix[Range[#], # - 3] & /@ Range[3] // Plus @@ # &

(*Method 3*)    
Table[FromDigits@Range[n] 10^(3 - n), {n, Range[3]}] // IntegerDigits

(*Method 4*)
10^Range[0, 2] // Map[# Quotient[FromDigits@Range[3], #] &] // 
  Reverse // IntegerDigits

Out:

{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.