Jan 29, 2008

Tip: Mathematica version of Maltab "Find" Function

I must say that if you work with Matlab everyday, it is really frustrated with Mathematica in some points.

Find is one of the most frequently used functions in Matlab.
Find(array>5.0): returns indices of the elements that are greater than 5.0.

In Mathematica, the corresponding function is Position

Position[array, #>5.0&] or Position[array, _>5.0] just doesn't work.

We "simple-minded" Matlab user have seldom thought about putting constraints on patterns

Then, this will do the job

Position[array, x : _ /; x > 5.0]

Position[array, x:_ /; testfunc[x]]
will do better.


Anonymous said...

You can save one character as the colon is not needed, i.e. use


Tony Mannucci said...

Here is my take. It's important to understand so that it can be generalized.
/; is called "Condition". It returns a pattern match only if the condition (the thing after /;) evaluates to true. The part "x_" means "name the pattern Blank by x so I can refer to the matched pattern later." Blank matches any expression.

To understand conditions, see "relational and logical expressions".

So, you can extend this as follows:
Position[array, x_ /; (x > 5) && (x < 10)]