I have two datasets, named as data1 and data2. The elements of two data sets are different. I want to collect the element of column2 of data1 when the element of column1 of data1 be the equal as the element of column1 of data2. I have written a code for that.It is as follows:

data1 = Table[{i, Sin[i]}, {i, 1, 10, 0.01}];
data2 = Table[{i, Cos[i]}, {i, 1, 10, 0.06}];
expecteddata = 
   Table[If[Transpose[data1][[1]][[i]] == Transpose[data2][[1]][[j]], 
     Transpose[data1][[2]][[i]], 0], {i, 1, Length[data1]}], # != 
     0 &], {j, 1, Length[data2]}]

This code provides the output what I want. But it takes too much time to execute if the datasets are large. So has there any other way to get it faster? Any suggestion will be helpful for me. Thanks in advance!


1 Answer 1


Either of the following:

Select[data1, MemberQ[data2[[All, 1]], #[[1]]] &][[All, 2]]
Pick[data1, MemberQ[data2[[All, 1]], #[[1]]] & /@ data1][[All, 2]]

returns the same elements as your code, but without the "double-listing", i.e. the output is:

{0.841471, 0.872355, 0.9001, 0.924606, ... , -0.385013, -0.492728, -0.544021}

If you'd prefer to have each value enclosed in a list, then modify that to List/@ Select[...][[All, 2]].


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.