MyList[[ 1, 3, 2 ]] using ind = {1, 3, 2}

  • Context: Mathematica 
  • Thread starter Thread starter Swamp Thing
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 2K views
Swamp Thing
Insights Author
Messages
1,062
Reaction score
819
Given a list of indices ind = {1, 3, 2} , is there a shortcut to this? :--
Code:
MyList[[ ind[[1]], ind[[2]], ind[[3]] ]]
 
Physics news on Phys.org
Not list comprehension, but something much simpler.

It's about Mathematica, indexing into a list.

Normally, you do MyList [[ m, n, o ]] when the indices m, n, o are available in variables. But if m, n, o are contained in a list like lst={1,3,2} then is there a more compact alternative to the code in my OP?
 
Swamp Thing said:
Normally, you do MyList [[ m, n, o ]] when the indices m, n, o are available in variables. But if m, n, o are contained in a list like lst={1,3,2} then is there a more compact alternative to the code in my OP?
In MATLAB, syntax like arr(ind) is accepted, where ind is an array of indexes of arr.

Matlab:
>> arr1 = [5 9 10 7 6 ];
>> ind = [1 3 2];
>> arr1(ind)

ans =

     5    10     9

Have you tried something like MyList [[ lst ]], a rough equivalent of the above MATLAB code?
 
Swamp Thing said:
Given a list of indices ind = {1, 3, 2} , is there a shortcut to this? :--
Code:
MyList[[ ind[[1]], ind[[2]], ind[[3]] ]]
Code:
MyList[[ Sequence @@ ind ]]
 
  • Informative
  • Like
Likes   Reactions: Swamp Thing, Wrichik Basu and topsquark
Wrichik Basu said:
Have you tried something like MyList [[ lst ]], a rough equivalent of the above MATLAB code?
If MyList is multidimensional, the above will pull out rows 1, 3 and 2. What I'm looking for is to pull out the single element MyList[[1, 3, 2]].

DrClaude said:
MyList[[ Sequence @@ ind ]]
Thank you.
I'm now experimenting with @@, which I am meeting here for the first time.
What is going on here:
Code:
Sqrt @@ Sin[2]
Output:
##\sqrt{2}##

Code:
Sqrt @@ Sin[2.0001]
Output:
0.909256
 
Try FullForm on what you put right of @@.

Code:
FullForm[Sin[2]]

FullForm[Sin[2.0001]]
 
  • Like
Likes   Reactions: Swamp Thing