Search code examples
mathwolfram-mathematicaphysicschemistry

Searching matrices in Mathematica 8 - Trying to find other elements on the same row as X


The text in italics describes my general goal, if anyone is interested. Question is underneath.

I am trying to graph the energy levels of simple molecules using Mathematica 8. My method is crude, and goes as this:

  1. Find eigenvalues of simple Hückel matrix.
  2. Delete duplicates and determine size of list.
  3. Evaluate the number of degeneracies by comparing duplicate list with no-duplicate list.
  4. Create a n x 2 zero matrix where n is the number of unique energy levels.

5. Fill first column with unique energy levels, second column with degeneracies.

The matrix generated in step 5 can look like this:

(1  2)
(3  1)   ==    M
(-1 1)

I wish to evaluate the maximum of column 2, and then find the value of the element in the same row, but in column 1. In this case, the answer I am looking for is 1.

These commands both evaluate to -1:

Extract[M[[All, 1]], M[[Max[M[[All, 2]]], 1]]]
M[[Max[M[[All, 1]]], 1]]

which is not the answer I want.

Any tips?

EDIT: This

Part[Part[Position[M, Max[M[[All, 2]]]], 1], 1]

works, but I don't understand why I have to use Part[] twice.


Solution

  • The inner Part gives you the first occurance of the maximum. Position returns a list of positions, even if there is only one element that has the maximum value, like this:

     M = {{2, 2}, {2, 3}, {2, 2}, {1, 1}}
    
     {{2, 2}, {2, 3}, {2, 2}, {1, 1}}
    
    Position[M, Max[M[[All, 2]]]]
    
     {{2, 2}}
    

    So you want the first element in the first element of this output. You could condense your code like this:

    Position[M, Max[M[[All, 2]]]][[1, 1]]
    

    However, one thing that I think your code needs to handle better is this case:

     M = {{3, 2}, {2, 3}, {2, 2}, {1, 1}}
    
    3, 2}, {2, 3}, {2, 2}, {1, 1}}
    
    Position[M, Max[M[[All, 2]]]]
    
    {{1, 1}, {2, 2}}
    

    You will get the wrong answer with your code in this case.

    Better would be:

    M[[All, 1]][[Position[M[[All, 2]], Max[M[[All, 2]]]][[1, 1]] ]]
    

    Or alternatively

    M[[Position[M[[All, 2]], Max[M[[All, 2]]]][[1, 1]], 1]]