2
$\begingroup$

I am trying to extract from a list L the elements

Extract[L, {i, j}]

where {i, j} are defined beforehand in a list, i.e., {{i1, j1},{i2, j2}, ...}.

Is there a way to let mathematica save this expression and not output the error below?

Extract::psl1: Position specification {i, j} in Extract[L,{i, j}] is not applicable.
$\endgroup$
1

4 Answers 4

3
$\begingroup$

First, never use upper-case letters to name a variable as it may conflict with an internal function or constant name.

Indexed[L, #] & /@ {{4, 5}, {2, 1}}
$\endgroup$
5
  • $\begingroup$ Sorry. I should have clarified that {i, j} are iterated variables say from $1$ to $n$. $\endgroup$
    – user54314
    Dec 20, 2017 at 22:12
  • $\begingroup$ Isn't this then just retrieving L in its entirety?? WHAT are you really trying to do? Please give a concrete example... not the vague and misleading explanation that has potential helpers confused. $\endgroup$ Dec 20, 2017 at 22:14
  • $\begingroup$ The indices are taken from a list coords = {{i1, j1}, ..., {in, jn}}, and I'm trying to get the list {L[[i1, j1]], ..., L[[in, jn]]}. $\endgroup$
    – user54314
    Dec 20, 2017 at 22:25
  • 1
    $\begingroup$ @user54314 list[[#[[1]], #[[2]]]] & /@ coords $\endgroup$
    – Alucard
    Dec 20, 2017 at 23:14
  • 1
    $\begingroup$ Or list[[Sequence @@ #]] & /@ coords. Note: edit your question instead of clarifying it in a comment. $\endgroup$
    – anderstood
    Dec 20, 2017 at 23:16
1
$\begingroup$
mL = RandomInteger[100, {50, 50}];
mCoords = RandomInteger[50, {25, 2}];
Extract[mL, mCoords]
$\endgroup$
1
$\begingroup$

Based on your comment above:

coords={{4, 5}, {2, 1}}
Table[{ip,jp}=pair; L[[ip,jp]],{pair,coords}]
$\endgroup$
1
  • $\begingroup$ Or Table[L[[Sequence@@pair]],{pair,coords}]. $\endgroup$
    – anderstood
    Dec 20, 2017 at 23:17
0
$\begingroup$

If you have a matrix

SeedRandom[1]
l = RandomInteger[10, {20, 20}];

and a list of positions of the elements you want to extract

pos = RandomInteger[{1, 20}, {10, 2}];

Then

l[[##]] & @@@ pos

is probably the easist way to go.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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