9
$\begingroup$

Is there is a performat way to convert something like

{{0,0},a},{{0,1},c},{{1,0},d},{{1,1},e}

into

{{a,b},{c,d}}

The indices are not always orderes and the only solution I can think of is searching for the maximum indices, create a matrix filled with 0 and use map afterwards to modify the matrix. Is there is a better way?

Thank you, Martin

$\endgroup$
  • 2
    $\begingroup$ I assume that when you write {{0,0},a},{{0,1},c},{{1,0},d},{{1,1},e} you actually mean {{{0, 0}, a}, {{0, 1}, b}, {{1, 0}, c}, {{1, 1}, d}}, Please check that the input is correct. $\endgroup$ – rhermans Jul 17 at 14:14
13
$\begingroup$
spec = {{{0, 0}, a}, {{0, 1}, b}, {{1, 0}, c}, {{1, 1}, d}};

Normal @ SparseArray[# + 1 -> #2 & @@@ spec]

{{a, b}, {c, d}}

$\endgroup$
8
$\begingroup$

Also possible:

r = {{{0, 0}, a}, {{0, 1}, c}, {{1, 0}, d}, {{1, 1}, e}};
SparseArray[r[[All, 1]] + 1 -> r[[All, 2]]]
$\endgroup$
1
$\begingroup$
(Array[{#1, #2} &, {2, 2}]-1)/.Rule@@@list

{{a, b}, {c, d}}

where

list={{{0, 0}, a}, {{0, 1}, b}, {{1, 0}, c}, {{1, 1}, d}};
$\endgroup$
  • $\begingroup$ I think you misinterpret the question. The index may not be limited by 2. $\endgroup$ – rhermans Jul 17 at 18:05

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.