开发者

Converting 1D list to 3D list

I have function which converts a 1D list to a 3D list, but at the same time when 2nd and 3rd dimension indices are equal it places zeroes instead of 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'd like to ge开发者_开发百科t rid of the Increment[] (++) function.


I think this may work:

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

Perhaps someone more savvy may help to get rid of the Partition[Partition nasty construction.

HTH!


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜