MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to find the index of a maximal element in a list?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg72955] Re: How to find the index of a maximal element in a list?
  • From: "Mark Westwood" <markc.westwood at gmail.com>
  • Date: Fri, 26 Jan 2007 07:06:35 -0500 (EST)
  • References: <epa2rr$iue$1@smc.vnet.net>

Hi Victor

No, off the top of my head I couldn't think of a neater way of doing
this, but I'm not sure that I am or should be bothered.  I created a
randomly ordered list of the first 500000 integers, and used your
approach to find the position of the maximum element.  Fast enough for
my purposes

In[10]:=list3=RandomPermutation[500000];

In[11]:=Timing[Position[list3,Max[list3]]]

Out[11]={0.094 Second,{{180740}}}

Why do you think that this approach traverses the list twice ?  I could
write it in Fortran with a single traversal of the list, something like
this (WARNING: untested code follows):

integer, dimension(500000) :: alist

maxelement = alist(1)
maxelement_location = 1

do i = 2, size(alist)
    if (alist(i) > maxelement) then
        maxelement = alist(i)              ! not required if you're
only looking for a position
        maxelement_location = i
    end if
end do


Of course, if I was writing it in Fortran I'd use the maxloc intrinsic
...

Regards
Mark Westwood


On 25 Jan, 11:04, Valter Sorana <vsor... at yahoo.com> wrote:
> I may have a mental block, but I cannot find anything better than
>
> Position[listName,Max[listName]]
>
> that traverses the list twice - once to find the maximum and once to find where it is.
>
> Isn't there a way to get both the index and the max value in one go?
>
> (of course one could write a loop that does this, but I want to avoid loops)
> 
> Thanks,
> 
> Valter.


  • Prev by Date: Re: [TS 1774]--Re:Wolfram Workbench: SVN & notebook diffs
  • Next by Date: Re: Re: pdf
  • Previous by thread: Re: How to find the index of a maximal element in a list?
  • Next by thread: Re: How to find the index of a maximal element in a list?