Re: Replace elements in a matrix
- To: mathgroup at smc.vnet.net
- Subject: [mg116468] Re: Replace elements in a matrix
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Wed, 16 Feb 2011 04:36:23 -0500 (EST)
On 2/15/11 at 6:32 AM, kp.0987 at gmail.com (kiz_0987) 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? Here is one way In[19]:= b + Unitize[a - 1] (a - b) Out[19]= {{0, 3}, {2, 2}} Unitize makes all non-zero entries 1. So, in each position where a is 1, the expression above becomes b + 0 = b and for each position where a is not 1 it becomes b + (a -b) = a