Re: Matrix manipulation
- To: mathgroup at smc.vnet.net
- Subject: [mg17024] Re: [mg16956] Matrix manipulation
- From: BobHanlon at aol.com
- Date: Wed, 14 Apr 1999 02:11:46 -0400
- Sender: owner-wri-mathgroup at wolfram.com
In a message dated 4/8/99 11:01:46 AM, maa.150 at rsk.dk writes: >question : I have 2 matrices with 2 coulomns each. >The first have 57 rows and the other 200 rows. >The first coulomn in each matrix contains ID numbers and I >would like to compare the two matrices and make a new matrix >containing the ID number and the numbers in the second row , so >the new matrix will be with 3 coulomns and 57 rows. >how to do that ? > Here is one approach: Generating random data of the form: {ID_Integer, data_Real} dataList1 = Union[Table[{Random[Integer, {100, 999}], Random[]}, {100}], SameTest-> (#1[[1]] == #2[[1]]&)]; dataList2 = Union[Table[{Random[Integer, {100, 999}], Random[]}, {50}], SameTest-> (#1[[1]] == #2[[1]]&)]; These lists are already sorted by ID due to the use of Union to eliminate duplicate IDs from the random data. If your list is not sorted by ID, use dataList1 = Sort[dataList1, #1[[1]] < #2[[1]]&]; dataList2 = Sort[dataList2, #1[[1]] < #2[[1]]&]; The ID numbers which are common to the two lists are idList = Intersection[Transpose[dataList1][[1]], Transpose[dataList2][[1]]]; The elements of the data lists which have the common IDs are subList1 = Select[dataList1, MemberQ[idList, #[[1]]]&]; subList2 = Select[dataList2, MemberQ[idList, #[[1]]]&]; Merging the lists result = {#[[1, 1]], #[[1, 2]], #[[2, 2]]}& /@ Transpose[{subList1, subList2}]; Or, if you want to doublecheck that only elements with common IDs are merged result2 = Cases[Transpose[{subList1, subList2}], {{x_, y1_}, {x_, y2_}} -> {x, y1, y2}]; result == result2 True Note that none of the operations made explicit use of the length of the lists; consequently, they will work with lists of any length. All of these steps can be combined into a single procedure which would accept two input lists and output the merged list. Bob Hanlon