Say I have a list of 4 integers valList = { v[1], v[2], v[3], v[4] }
whose values may or may not be equal to one another. Now I would like to extract all rows from a matrix such that if the i'th value of valList
equals the j'th value of valList
then the i'th value of the row should also be equal to the j'th value of that row.
So if, e.g., v[1] == v[2]
, v[3]==v[4]
, and v[3]!=v[2]
then I want to keep only the four-tuples for which the first value equals the second and the third value equals the fourth. It should still be OK if the third value equals the second.
The idea I had was to write a function that converts the list valList
to a criterion for Select
but I don't see an elegant way to do this. At the moment I'm using
SelectViaEquality[ list_, mat_ ] :=
With[{
equalIndices = GatherBy[ Table[ i -> list[[i]], {i, 4}], Last][[;; , ;; , 1]] },
With[{
crit = Function[ row,
And @@ Equal @@@ Map[ Part[ row, #] &, equalIndices, {2} ]
] },
Select[ crit ] @ mat
]
];
This function is neither elegant, simple to read, or efficient since the crit function gets redefined with every call...
Question: is there an easy way to extract all rows from a matrix that satisfy the above requirements?