问题
I have a large matrix, let's call it A, which has dimension Mx3, e.g. M=4000 rows x 3 columns. Each row in the matrix contains three numbers, eg. [241 112 478]. Out of these three numbers, we can construct three pairs, eg. [241 112], [112 478], [241 478]. Of the other 3999 rows:
- For each of the three pairs, exactly one row of M (only one) will contain the same pair. However, the order of the numbers could be scrambled. For example, exactly one row will read: [333 478 112]. No other row will have both 478 and 112. I am interested in finding the index of that row, for each of the three pairs. The output should then be another matrix, call it B, with same dimensions 4000x3, where each row has the indices of the rows in the original matrix A that share a pair of numbers.
- No other row will contain the same three numbers.
- Other rows may contain none of the numbers or one of the numbers.
Here's a function that accomplishes this, but is very slow - I'd like to know if there is a more efficient way. Thanks in advance!
M=size(A,1); % no elements
B=zeros(M,3);
for j=1:M
l=1;
k=1;
while l<4 % there cant be more than 3
if k~=j
s=sum(ismember(A(j,:),A(k,:)));
if s==2
B(j,l)=k;
l=l+1;
end
end
k=k+1;
end
回答1:
For loops are not needed, just use ismember the following way:
row_id1=find(sum(ismember(M,[241 112]),2)>1);
row_id2=find(sum(ismember(M,[478 112]),2)>1);
row_id3=find(sum(ismember(M,[478 241]),2)>1);
each row_id will give you the row index of the pair in that line regardless of the order at which it appears.
The only assumption made here is that one of the pair numbers you look for will not appear twice in a row, (i.e. [112 333 112]). If that assumption is wrong, this can be addressed using unique.
来源:https://stackoverflow.com/questions/21642235/matlab-efficiently-find-the-row-that-contains-two-of-three-elements-in-a-large-m