 
 
 
 
 
 
Re: Simply but handy question
- To: mathgroup at smc.vnet.net
- Subject: [mg124852] Re: Simply but handy question
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Thu, 9 Feb 2012 05:41:09 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
On 2/8/12 at 5:29 AM, jediwhelan at googlemail.com (jediwhelan) wrote:
>I am new to mathematica (well, I'm not actually but I haven't used
>it in 5 years +).
>Is there an easy way to return a matrix X of 1's and 0's to test
>whether the entries in Y are different from zero.
>i.e.,
>if Y = {{a,b},{0,c}}
>Then X would return
>X = {{1,1},{0,1}}
If the non-zero entries have numeric values, Unitize will do
what you want. For example:
In[1]:= {a, b, c} = RandomReal[1, {3}];
y = {{a, b}, {0, c}};
Unitize[y]
Out[3]= {{1, 1}, {0, 1}}
If there are symbols that do not have numeric values assigned,
then Unitize won't do. You would need to use pattern matching to
replace these symbols. Something like:
In[4]:= Clear[a, b, c, y];
y = {{a, b}, {0, c}};
Map[# /. a_Symbol -> 1 &, y, {2}]
Out[6]= {{1, 1}, {0, 1}}
Note, while this will work for symbolic arrays it will be
considerably slower than using Unitize with large numeric arrays.
>This would be handy for very large or complicated matrices where one
>would like to know if specific entries are zero?
For very large arrays with few zeros and numeric entries, I
would locate the zeros by
ArrayRules@SparseArray[Unitize[matrix]-1]
Also, you might consider
ArrayPlot[Unitize[matrix]]
For very large arrays, with quite a few zeros this will probably
be the best way to visualize where the zeros are.

