Re: For Routine to Map Routine
- To: mathgroup at smc.vnet.net
- Subject: [mg70417] Re: For Routine to Map Routine
- From: "Ray Koopman" <koopman at sfu.ca>
- Date: Mon, 16 Oct 2006 02:34:11 -0400 (EDT)
- References: <egse9i$css$1@smc.vnet.net>
Benedetto Bongiorno wrote:
> To All,
>
> Dimensions of ans01 is 2185850 by 5.
> I am looking to convert my For routine to the more efficient Map routine
>
> n=Length[ans01]
> fo={};
>
> For[i=1, i<n, i++,
> If[ans01[[i,1]] == ans01[[i+1,1]],
> AppendTo[fo, ans01[[1]]]];
>
> I tried
> Map[If[#[[1]] == #[[1]],#]&,ans01];
>
> But it does not work.
>
> Thank you
>
> Ben
I interpret your code as saying that you want the rows of ans01
whose first element is the same as the first element in the next row.
In a previous thread, Carl Woll wrote:
| The fastest approach for selecting a conditional subset of a large
| data set usually works as follows:
| 1. Construct a list of 0's and 1's corresponding to which elements
| you want to keep.
| 2. Extract the position of the 0's or 1's.
| 3. Use Part to obtain the subset.
Also, operating on entire vectors is usually faster than operating on
elements of vectors inside a loop. Applying those recommendations:
c = ans01[[All,1]] gives the first column of ans01.
d = Most@c-Rest@c gives the vector of differences between successive
terms in c. This is coded below as (Most@#-Rest@#&)[c].
u = UnitStep[-Abs[d]] gives 1 where d=0, and gives 0 everywhere else.
p = SparseArray[u]/.SparseArray[_,_,_,p_]:>Flatten[p[[2,2]]]
gives the positions of the 1's in u.
ans01[[p]] gives the rows of ans01 that you want.
Putting it all together:
ans01[[SparseArray[UnitStep[-Abs[(Most@#-Rest@#&)[ans01[[All,1]]]]]]/.
SparseArray[_,_,_,p_]:>Flatten[p[[2,2]]]]]