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

Randomly select Elements of 4D matrix in Matlab

Ray Phan
Jun 24, 2015
<p>If I am interpreting what you want correctly, for each unique 3D position in this matrix of 7 x 4 x 24, you want to be sure that we randomly sample from one out of the 10 stacks that share the same 3D spatial position.</p> <p>What I would recommend you do is generate random integers that are from 1 to 10 that is of size 7 x 4 x 24 long, then use <a href="http://www.mathworks.com/help/matlab/ref/sub2ind.html" rel="nofollow"><code>sub2ind</code></a> along with <a href="http://www.mathworks.com/help/matlab/ref/ndgrid.html" rel="nofollow"><code>ndgrid</code></a>. You can certainly use <code>randi</code> as you have alluded to in the comments.</p> <p>We'd use <code>ndgrid</code> to generate a grid of 3D coordinates, then use the random integers we generated to access the fourth dimension. Given the fact that your 4D matrix is stored in <code>A</code>, do something like this:</p> <pre><code>rnd = randi(size(A,4), size(A,1), size(A,2), size(A,3)); [R,C,D] = ndgrid(1:size(A,1), 1:size(A,2), 1:size(A,3)); ind = sub2ind(size(A), R, C, D, rnd); B = A(ind); </code></pre> <p>Bear in mind that the above code will work for <strong>any</strong> 4D matrix. The first line of code generates a 7 x 4 x 24 matrix of random integers between <code>[1,10]</code>. Next, we generate a 3D grid of spatial coordinates and then use <code>sub2ind</code> to generate column-major indices where we can sample from the matrix <code>A</code> in such a way where each unique 3D spatial location of the matrix <code>A</code> only samples from one chunk and only one chunk. We then use these column-major indices to sample from <code>A</code> to produce our output matrix <code>B</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30959721/Randomly%20select%20Elements%20of%204D%20matrix%20in%20Matlab/30959934">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus