Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: Elegant syntax for multiple conditional assignment?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg54409] Re: [mg54337] Elegant syntax for multiple conditional assignment?
  • From: Bob Hanlon <hanlonr at cox.net>
  • Date: Sun, 20 Feb 2005 00:08:18 -0500 (EST)
  • Reply-to: hanlonr at cox.net
  • Sender: owner-wri-mathgroup at wolfram.com

old={a1,c1,x1,y1};

new={a2,c2,x2,y2};

cond={True,False,True,False};

{a,c,x,y} = If[#[[1]],#[[2]],#[[3]]]&/@
    Transpose[{cond,new,old}]

{a2,c1,x2,y1}

{a,c,x,y} = If[#[[1]],#[[2]],#[[3]]]&/@
    Thread[{cond,new,old}]

{a2,c1,x2,y1}


Bob Hanlon

> 
> From: Scott Hemphill <hemphill at hemphills.net>
To: mathgroup at smc.vnet.net
> Date: 2005/02/19 Sat AM 02:31:38 EST
> To: mathgroup at smc.vnet.net
> Subject: [mg54409] [mg54337] Elegant syntax for multiple conditional assignment?
> 
> Dear Mathematica aficionados:
> 
> I have several state variables, each of which is a vector of "n" elements.
> I would like to assign each element in each vector based on a condition
> which is in the corresponding position in a condition vector.  To be more
> specific:
> 
>   Each of a, c, x and y is a List of Length n.
>   cond is a List of Length n, containing True and False values
> 
> What I have is
> 
>   old = {a, c, x, y};
> 
>   code which changes a, c, x, and y
> 
>   new = {a, c, x, y};
> 
> What I want to do is assign to each element of a, c, x and y the old value
> of a, c, x or y if the corresponding element of cond is False, and the new
> value of a, c, x or y if the corresponding element of cond is True.
> 
> I've got a method that works:
> 
> t=Transpose;
> {a, c, x, y} = t[If[#[[1]],#[[2]],#[[3]]]& /@ t[{cond,t[new],t[old]}]];
> 
> All the transpositions and array indexing make me wonder if there's a more
> elegant way of expressing this.
> 
> Any takers?  Thanks in advance.
> 
> Scott
> -- 
> Scott Hemphill	hemphill at alumni.caltech.edu
> "This isn't flying.  This is falling, with style."  -- Buzz Lightyear
> 
> 


  • Prev by Date: Re: Elegant syntax for multiple conditional assignment?
  • Next by Date: Re: real telescopic sum becomes complex?
  • Previous by thread: Re: Elegant syntax for multiple conditional assignment?
  • Next by thread: Re: Elegant syntax for multiple conditional assignment?