MathGroup Archive 2009

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

Search the Archive

Re: put some elements to zero

  • To: mathgroup at smc.vnet.net
  • Subject: [mg101484] Re: put some elements to zero
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Wed, 8 Jul 2009 07:12:43 -0400 (EDT)

On 7/7/09 at 7:46 AM, L.Balzano at gmail.com (Luigi B) wrote:

>I have a matrix with only two columns and many rows. For instance
>{xi,yi}. For those xi<x0, I would like to set yi=0. I can only think
>of a very inefficient loop...

One way would be to use pattern matching as follows:

=46irst generate a sample data set

In[1]:= data = RandomInteger[10, {5, 2}]

Out[1]= {{7, 0}, {6, 8}, {4, 5}, {5, 5}, {8, 8}}

Then modify it using the code below

In[2]:= data /. {a_, b_} :> If[a < 5, {a, 0}, {a, b}]

Out[2]= {{7, 0}, {6, 8}, {4, 0}, {5, 5}, {8, 8}}

As you can see the pair {4,5} got changed to {4,0} and all other
pairs were left as is.

I used RuleDelayed and a specific test for the first element
being less than 5 since I think this makes it very clear what
the code will do. But the pattern could be written to only match
pairs with the first element < 5 as follows:

In[3]:= data /. {a_?(# < 5 &), _} -> {a, 0}

Out[3]= {{7, 0}, {6, 8}, {4, 0}, {5, 5}, {8, 8}}




  • Prev by Date: Re: Re: Fast calculation of pair correlation function
  • Next by Date: Re: AbsoluteOptions for BarChart
  • Previous by thread: Re: put some elements to zero
  • Next by thread: Re: put some elements to zero