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

How can I find all the cells that have the same values in a multi-dimensional array in octave / matlab

Ray Phan
Jul 09, 2015
<p>Use <code>bsxfun</code>(<a href="http://www.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow">MATLAB doc</a>, <a href="https://www.gnu.org/software/octave/doc/interpreter/Broadcasting.html" rel="nofollow">Octave doc</a>) and check to see if broadcasting the first slice is equal across all slices with a call to <code>all</code>(<a href="http://www.mathworks.com/help/matlab/ref/all.html" rel="nofollow">MATLAB doc</a>, <a href="https://www.gnu.org/software/octave/doc/interpreter/Finding-Elements-and-Checking-Conditions.html#XREFall" rel="nofollow">Octave doc</a>):</p> <pre><code>B = bsxfun(@eq, A, A(:,:,1)); result = all(B, 3); </code></pre> <p>If we're playing <a href="https://en.wikipedia.org/wiki/Code_golf" rel="nofollow">code golf</a>, a one liner could be:</p> <pre><code>result = all(bsxfun(@eq, A, A(:,:,1)), 3); </code></pre> <p>The beauty of the above approach is that you can have as many slices as you want in the third dimension, other than just three.</p> <h1>Example</h1> <pre><code>%// Your data A(:,:,1)=[1 2 3; 4 5 6; 7 9 8]; A(:,:,2)=[9 1 7; 6 5 4; 7 2 8]; A(:,:,3)=[2 4 6; 8 9 1; 3 5 8]; B = bsxfun(@eq, A, A(:,:,1)); result = all(B, 3); </code></pre> <p>... gives us:</p> <pre><code>&gt;&gt; result result = 0 0 0 0 0 0 0 0 1 </code></pre> <p>The above makes sense since the third row and third column for all slices is the only value where every slice shares this same value (i.e. 8).</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31255059/How%20can%20I%20find%20all%20the%20cells%20that%20have%20the%20same%20values%20in%20a%20multi-dimensional%20array%20in%20octave%20/%20matlab/31255485">Stack Overflow</a>.</p>
comments powered by Disqus