MathGroup Archive 2011

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

Search the Archive

Re: Replace elements in a matrix

  • To: mathgroup at smc.vnet.net
  • Subject: [mg116464] Re: Replace elements in a matrix
  • From: Armand Tamzarian <mike.honeychurch at gmail.com>
  • Date: Wed, 16 Feb 2011 04:35:40 -0500 (EST)
  • References: <ijdo8r$f7a$1@smc.vnet.net>

On Feb 15, 10:32 pm, kiz_0987 <kp.0... at gmail.com> wrote:
> I'm new to Mathematica and have a question regarding matrices. I was
> sure that this problem must have been answered in the past, but could
> not find a solution.
>
> I want to replace some elements in a matrix (based on value) with
> elements from another matrix at the same position. Eg:
> a = {{0, 1}, {1, 2}};
> b = {{1, 3}, {2, 5}};
>
> I want to replace the elements in "a" which are equal to 1 (say) with
> the same position elements in b to give:
> c = {{0, 3}, {2, 2}};
>
> How can I do this? I started with using Position and ReplacePart but
> could not figure out how to get it to work in this case (other cases
> are documented, such as replacing with a single value).
>
> Any help appreciated. Thanks.

There may be a more elegant way but this works:

transform[a_, b_, value_] := Module[{pos, c = a},

  pos = Position[c, value];
  (c[[Sequence @@ #]] = b[[Sequence @@ #]]) & /@ pos;

  c]

In[]= transform[a, b, 1]

Out[]= {{0, 3}, {2, 2}}

Mike


  • Prev by Date: Solids of revolution
  • Next by Date: Re: NInegrate Bug
  • Previous by thread: Re: Replace elements in a matrix
  • Next by thread: Re: Replace elements in a matrix