Re: matrix problem
- To: mathgroup at smc.vnet.net
- Subject: [mg107134] Re: matrix problem
- From: dr DanW <dmaxwarren at gmail.com>
- Date: Wed, 3 Feb 2010 06:13:18 -0500 (EST)
- References: <hk93ca$f68$1@smc.vnet.net>
Here is the most straightforward way to do this: m = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; n = {{1, 8}, {5, 0}, {9, 7}}; m1 = Select[m, Function[x, MemberQ[Union[ n[[All,1]] ], x[[1]] ] ] ] n1 = Select[n, Function[x, MemberQ[Union[ m[[All,1]] ], x[[1]] ] ] ] First, avoid using capitals for variable names; N is a function name in Mathematica. The rest of this is a lot to swallow in one go, so lets break it down. n[[All,1]] is a list of that is the first element of all rows, also known as the first column Union[ n[[All,1]] ] is a list of all the unique members of that list. Unnecessary in this case, but good programming practice. MemberQ[Union[ m[[All,1]] ], x[[1]] ] tests to see if the first member of x is a member of that list Function[x, MemberQ[Union[ m[[All,1]] ], x[[1]] ] ] makes a function out of it, which takes one parameter, x. Finally Select[m, Function[x, MemberQ[Union[ n[[All,1]] ], x[[1]] ] ] ] selects all elements out of m which match the criterion as laid out in the Function. Mathematica eats this kind of thing for lunch. Study this example, because once you get used to this kind of thinking, you can really exploit the power of Mathematica. Daniel