MathGroup Archive 2009

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

Search the Archive

Re: Comparing Corresponding Columns of Two Matrices


Here is one method. Whenever I want to perform some operation on two equal
length vectors I think of the Inner command. In your problem we are going to
apply this twice, once to compare the elements in two columns, and once to
accumulate a list of results for all the columns.

Here is a routine to compare the elements in two columns, each column given
by a list, to see if all the elements in the first column are greater than
the corresponding elements in the second column.

greaterColumn[column1_, column2_] := 
 Inner[#1 > #2 &, column1, column2, And]

Try it out on two cases.

greaterColumn[{2, 3, 4, 5}, {1, 2, 3, 4}]

greaterColumn[{2, 3, 4, 5}, {1, 6, 3, 7}]

The following will generate text xmat and ymat matrices. I make them only 8
rows long instead of 100. I also bias xmat to be greater than ymat so that
we might get some True conditions.

(xmat = Table[
    RandomInteger[{3, 7}], {x, 1, 8}, {y, 1, 4}]) // MatrixForm
(ymat = Table[
    RandomInteger[{0, 5}], {x, 1, 8}, {y, 1, 4}]) // MatrixForm

The following then compares the two matrices column by column.

Inner[greaterColumn[#1, #2] &, f @@ Transpose[xmat], 
 f @@ Transpose[ymat], List]

There is one caveat or trick that I have used. For arrays, Inner works like
Dot and this is not what we want. We want the two items to look like vectors
and not arrays, so I used f@@ on the transposed matrices to change the outer
List brackets to f, and now they no longer look like 2-dimensional arrays,
but like 1-dimensional vectors.

David Park
djmpark at  

From: Gregory Lypny [mailto:gregory.lypny at] 

Hello everyone,

I'm trying to develop a modest skill in mapping functions and I've  
been working on this problem.

Suppose I have two 100 x 4 matrices, X and Y, and I want to see  
whether each value in a column of X is bigger than each value in the  
corresponding column of Y.  In other words, compare column 1 of X with  
column 1 of Y, column 2 of X with column 2 of Y, and so on.

It's easy to generate a 100 x 4 table of Booleans using Table as

	Table[Boole[X[[i ,  j]] > Y[[i, j]]], {i, 100}, {j, 4}]

But what about without Table?  I am able to do it for the comparison  
of any one column as

	Boole[#[[1]] > #[[2]]] & /@ Transpose[{X[[All, ]], Y[[All, 1]]}]

but I'm not sure how to extend this to other columns.  Any tip would  
be much appreciated.



  • Prev by Date: Re: Mathematica Question - Using DSolve with Boundary Conditions
  • Next by Date: Re: A newbee to Mathematica
  • Previous by thread: Re: Comparing Corresponding Columns of Two Matrices
  • Next by thread: Re: Comparing Corresponding Columns of Two Matrices