Common Non-Zero Elements Among 5 Arrays
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuesta aceptada
Matt Fig
el 7 de Jun. de 2011
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...
Más respuestas (1)
Walter Roberson
el 7 de Jun. de 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 comentarios
Walter Roberson
el 7 de Jun. de 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?
Ver también
Categorías
Más información sobre Numeric Types en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!