Re: Handling conditions on subvector elements
- To: mathgroup at smc.vnet.net
- Subject: [mg117582] Re: Handling conditions on subvector elements
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Wed, 23 Mar 2011 02:55:42 -0500 (EST)
On 3/22/11 at 5:05 AM, lt648 at hszk.bme.hu (Lengyel Tamas) wrote: >I am struggling with a piece of code which should result in a List : >1) I have a vector with subvectors with triplets of values. 2) What >I wish to achieve is a cycle that returns with a List with either >'1's or '2's in it. 3) The cycle should check whether the first and >second element in subvectors are equal and neither of them are equal >with the third, if so, return 1; >If all the elements are unequal, return 2 >E.g. >V= {{1,1,2},{1,1,3},{2,3,1},{1,2,3},{3,3,1}} should return with {1, >1, 2, 2,1} >I'm assuming 'If' should be the key (as it returns 2 types of >values), but I can't seem to do it properly. Here are a few ways to achieve what you want. First using If In[2]:= If[Length[Union[#]] == 3, 2, 1] & /@ v Out[2]= {1,1,2,2,1} Next using pattern matching In[3]:= v /. {{___, a_, ___, a_, ___} -> 1, {a_, b_, c_} -> 2} Out[3]= {1,1,2,2,1} Note the order of the replacement rules is important. And finally a direct computation In[4]:= Length[Union[#]] - 1 & /@ v Out[4]= {1,1,2,2,1} Note this last is probably the fastest solution of the three here but is less general. The first two solutions will return 1 if all three elements are identical while this last will return 0 in that case.