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

  • Thread starter Thread starter Swamp Thing
  • Start date Start date
AI Thread Summary
The discussion focuses on finding a more efficient way to index elements in a list using Mathematica, specifically when the indices are stored in a separate list. The original method involves using individual indices, such as MyList[[ind[[1]], ind[[2]], ind[[3]]]]. A suggested alternative is using the Sequence function, represented as MyList[[Sequence @@ ind]], which allows for a more compact syntax. This approach is compared to MATLAB's indexing method, where an array of indices can be directly used to access elements. The conversation also touches on the use of the @@ operator in Mathematica, with examples demonstrating its application in mathematical functions. Overall, the key takeaway is the efficiency gained by using Sequence with a list of indices for element extraction in Mathematica.
Swamp Thing
Insights Author
Messages
1,028
Reaction score
766
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 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 Swamp Thing

Similar threads

Back
Top