       Re: Elegant syntax for multiple conditional assignment?

• To: mathgroup at smc.vnet.net
• Subject: [mg54416] Re: [mg54337] Elegant syntax for multiple conditional assignment?
• From: DrBob <drbob at bigfoot.com>
• Date: Sun, 20 Feb 2005 00:08:48 -0500 (EST)
• References: <200502190731.CAA05948@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```(inputs)
old = Array[o, {4}]
new = Array[n, {4}]
cond = Array[1 == Random[Integer, {0, 1}] & , {4}]

(outputs)
{o, o, o, o}
{n, n, n, n}
{True, False, True, False}

(input)

(result)
{n, o, n, o}

or:

old = {a, c, x, y} = Array[o, {4}]
new = {a, c, x, y} = old^2
cond = Array[1 == Random[Integer, {0, 1}] &, {4}]

{o, o, o, o}
{o^2, o^2, o^2, o^2}
{True, False, False, False}

{a, c, x, y} = Thread[If[cond, Evaluate@new, Evaluate@old]]

{o^2, o, o, o}

Bobby

On Sat, 19 Feb 2005 02:31:38 -0500 (EST), Scott Hemphill <hemphill at hemphills.net> wrote:

>
> 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[#[],#[],#[]]& /@ 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

--
DrBob at bigfoot.com
www.eclecticdreams.net

```

• Prev by Date: Re: Elegant syntax for multiple conditional assignment?
• Next by Date: Re: Re: Re: Re: Bug Report - Two numerical values for a same variable
• Previous by thread: Elegant syntax for multiple conditional assignment?
• Next by thread: Re: Elegant syntax for multiple conditional assignment?