Common Non-Zero Elements Among 5 Arrays
Show older comments
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).
Accepted Answer
More Answers (1)
Walter Roberson
on 7 Jun 2011
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 Comments
Greggory
on 7 Jun 2011
Walter Roberson
on 7 Jun 2011
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?
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!