Common Non-Zero Elements Among 5 Arrays
조회 수: 2 (최근 30일)
이전 댓글 표시
I have five 3-D arrays and I would like to find any elements that are common to 2 or more of the arrays and that are non-zero. I've tried doing something like:
mask = (dat1==dat2) | (dat1 == dat3) | (dat1 == dat4) | (dat1 == dat5) | (dat2 == dat3) | (dat2 == dat4) | (dat2 == dat5) | (dat3 == dat4) | (dat3 == dat5) | (dat4 == dat5);
but since zeros are common, I get an array of nearly all 1's. I'm trying to avoid just using a 'for' loop to step through all the non-zero elements and checking. There should only be about 50 or so common non-zero elements out of nearly 100,000 total elements.
Thank you for your time helping me.
EDIT: What I want to know is the location of the elements and I don't really care what the value is (as long as it isn't zero).
댓글 수: 0
채택된 답변
Matt Fig
2011년 6월 7일
I am still a uncertain if this is what you want, but here goes:
idx0 = (dat1==dat2 | dat1==dat3 | dat1==dat4 | dat1==dat5) & logical(dat1);
idx1 = (dat1==dat2 | dat2==dat3 | dat2==dat4 | dat2==dat5) & logical(dat2);
idx2 = (dat1==dat3 | dat2==dat3 | dat3==dat4 | dat3==dat5) & logical(dat3);
idx3 = (dat1==dat4 | dat2==dat4 | dat3==dat4 | dat4==dat5) & logical(dat4);
idx4 = (dat1==dat5 | dat2==dat5 | dat3==dat5 | dat4==dat5) & logical(dat5);
IDX = idx0 | idx1 | idx2 | idx3 | idx4
Now IDX has a 1 where two or more arrays share a non-zero value...
추가 답변 (1개)
Walter Roberson
2011년 6월 7일
U = {unique(dat1(:)), unique(dat2(:)), unique(dat3(:)), unique(dat4(:)), unique(dat5(:))};
C = [];
for J = 1:4
for K = J+1:5
C = union(C, intersect(U{J},U{K}));
end
end
C(C==0) = [];
Note that the text of your question asks to find common elements, which is what the above code does.
The code sample you give, though, is trying to find the positions that have common elements, and is restricting the possible commonality to corresponding array positions: you should clarify which meaning you intend.
Are your elements integral? If not then is there not concern about floating point round-off ?
댓글 수: 2
Walter Roberson
2011년 6월 7일
Are matches restricted to corresponding locations?
Are the values integral or should we be considering round-off error in the determination of whether the values are equal?
참고 항목
카테고리
Help Center 및 File Exchange에서 Numeric Types에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!