× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Fastest way of finding repeated values in different cell arrays of different size

Ray Phan
Feb 02, 2015
<p>Another possibility that I could suggest, though Luis Mendo's answer is very good, is to take all of the vectors in your cell array and remove the duplicates. This can be done through <a href="http://www.mathworks.com/help/matlab/ref/cellfun.html" rel="nofollow"><code>cellfun</code></a>, and specifying <a href="http://www.mathworks.com/help/matlab/ref/unique.html" rel="nofollow"><code>unique</code></a> as the function to operate on. You'd have to set the <code>UniformOutput</code> flag to false as we are outputting a cell array at each index. You also have to be careful in that each cell array is assumed to be all row vectors, or all column vectors. You can't mix the way the arrays are shaped or this method won't work.</p> <p>Once you do this, concatenate all of the vectors into a single array through <a href="http://www.mathworks.com/help/matlab/ref/cell2mat.html" rel="nofollow"><code>cell2mat</code></a>, then do a histogram through <a href="http://www.mathworks.com/help/matlab/ref/histc.html" rel="nofollow"><code>histc</code></a>. You'd specify the edges to be all of the unique numbers in the single array created before. Note that you'd have to make an additional call to <code>unique</code> on the output single array before proceeding. Once you calculate the histogram, for any entries with a bin count equal to the total number of elements in your cell array (which is 3 in your case), then these are values that you see in all of your cells. As such:</p> <pre><code>A = cell2mat(cellfun(@unique, indx, 'uni', 0)); edge_values = unique(A); h = histc(A, edge_values); result = edge_values(h == numel(indx)); </code></pre> <p>With the unique call for each cell array, if a number appears in every single cell, then the total number of times you see this number should equal the total number of cells you have.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25851305/Fastest%20way%20of%20finding%20repeated%20values%20in%20different%20cell%20arrays%20of%20different%20size/25851845">Stack Overflow</a>.</p>
comments powered by Disqus