Convert 1D list to 3D list

I have a function that converts a 1D list to a 3D list, but at the same time, when the indices of the 2nd and 3rd dimensions are equal, it puts zeros instead of the values ​​from the input list:

n = 4

input = Table[RandomInteger[5], {i, 1, 48}]

convert[l_] := Table[If[i == j, 0, l[[index++]]], {s, 1, 4}, {i, 1, n}, {j, 1, n}]

output = convert[input]

I want to get rid of the Increment [] (++) function.

+3
source share
2 answers

I think this might work:

convert[l_] := Insert[Partition[Partition[l, 3], 4], 0, 
                      Flatten[Table[{j, i, i}, {j, 4}, {i, 4}], 1]]

Perhaps someone more savvy can help get rid of the unpleasant construction of Partition [Partition ].

NTN!

+1
source

Here's an alternative (ab) using SparseArray, but it does not eliminate the need for an index variable and increases it:

convert[l_] := Module[{q=1},
  Normal[SparseArray[{{_,i_,i_} -> 0, {i_,j_,k_} :> l[[q++]]}, {3, 4, 4}]]
]
+1
source

Source: https://habr.com/ru/post/1772713/


All Articles