Suppose I have a cell
A = {[3,0], [2,1]}
and a cell array
B = {[4,-1],[3,0];
[-1,4],[-3,5];
[3,0],[2,1];
[2,1],[-1,4]}.
I want to find the indices where both the first or second entry in A shows up in B excluding the row in B where both entries of A show up.
In this example I should get something like [1 4] for the rows in B. I’ve been trying to figure this out using cellfun and cell2mat but keep stumbling.
I would approach this problem by converting my cell arrays to numeric arrays of appropriate dimensions, and then use
ismember.The following example illustrates how this method works on the example cell arrays in the question:
Some points:
1) This method finds the indices of all rows in
Bwhere an element ofAlies in the first or second column ofB, excluding the situation whereAcorresponds exactly to a row ofB.2) This method will fail if there are multiple rows in
A. However, it is robust toAbeing a cell array of size 1*N, where N denotes some arbitrary number of 1*2 numeric vectors. Thus the single row limitation can be circumvented by first reshapingAto a 1*N cell array.3) Equivalence is tested using the logical operator
==. This can be dangerous with floating point numbers unless you have reason to believe a priori that your inputs will not exhibit any floating point error.4) I can’t shake the feeling that there is a much more efficient way to solve this problem, but that I’m not seeing it at the moment. 🙂