Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: How can I perform Matrix comparison? Can any one with kindness help

  • To: mathgroup at smc.vnet.net
  • Subject: [mg114819] Re: How can I perform Matrix comparison? Can any one with kindness help
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Fri, 17 Dec 2010 23:49:25 -0500 (EST)

Hi,

For element-wise comparison of matrices with same dimensions, you can use
listability:

In[155]:=
Clear[elementwiseCompare]
elementwiseCompare[mat1_?MatrixQ, mat2_?MatrixQ, oper_] /;
   Equal @@ Map[Dimensions, {mat1, mat2}] :=
  Function[{m1, m2}, oper[m1, m2], Listable][mat1, mat2];


In[157]:= elementwiseCompare[{{a, b}, {c, d}}, {{e, f}, {g,
   h}}, Greater]

Out[157]= {{a > e, b > f}, {c > g, d > h}}

In[158]:= elementwiseCompare[{{a, b}, {c, d}}, {{e, f}, {g, h}}, Less]

Out[158]= {{a < e, b < f}, {c < g, d < h}}

With your matrices:

In[159]:= Block[{a = {{2, 3}, {4, 5}}, b = {{1, 2}, {2, 3}}},
 elementwiseCompare[a, b, Greater]]

Out[159]= {{True, True}, {True, True}}

If you need a single answer, can Flatten the resulting Boolean matrix and
Apply And:

In[160]:= And @@ Flatten[%]

Out[160]= True

Regards,
Leonid


On Fri, Dec 17, 2010 at 2:21 PM, Nasser M. Abbasi <nma at 12000.org> wrote:

> On 12/17/2010 12:29 AM, fmingu wrote:
> > I am using mathematica for practical purpose.
> > I wonder how can I perform Matrix comparison.
> > For instance:
> > a={{2,3},{4,5}}; b={{1,2},{2,3}};
> > a>b
> > I want the result is True.
>
> Based on what definition?
>
> Mathematica uses ">" for numbers, but you have a matrices to compare.
>
> > But it seems that Mathematica can not recognize it.
> > I do not know how I can solve it? Are there any additional package to be
> added?
> > Can any one with kindness help me?
>
> Normally one uses a matrix norm to compare matrices, but if
> you use element by element compare, you can use
> Map or Thread of one of those functions to compare
> corresponding elements.
>
> But one way I've done this before is by making a
> list of the corresponding elements of each matrix, then
> Map the operator on them. Using your example:
>
> lis=Inner[List,Flatten[a],Flatten[b],List]
>
>    {{2,1},{3,2},{4,2},{5,3}}
>
> Map[Greater,lis]
>
>    {True,True,True,True}
>
> There is I am sure a shorter way to do this without even
> making a list first.
>
> --Nasser
>
>


  • Prev by Date: Re: Lucas 1874 Fibonacci as binomial sum generalization problem
  • Next by Date: Query available max memory (RAM)?
  • Previous by thread: Re: How can I perform Matrix comparison? Can any one with kindness help
  • Next by thread: bibtex support in Mathematica 8