title: Assign different arrays to a 3D matrix in Matlab
body: <p>In matlab, I want a 3D matrix with random numbers that are unique along the 3th dimension, as this code does:</p>
  
  <pre><code>M = 2;  N = 10;  L = 5;  K = 100;
  mat = zeros([M N L]);
  for ii=1:M
      for jj=1:N
          mat(ii,jj,:) = randperm(K,L);
      end
  end
  </code></pre>
  
  <p>However, when the matrix is larger, the computation time rises a lot. Thus, I would like to delete the loop's with any vectorization. I couldn't figure it out any way of doing so, is it possible?</p>
  
  <p>Thank you for the help.</p>
  
  <hr>
  
  <p>Edit: I have run all the methods for several matrix sizes in this <a href="http://hostcode.sourceforge.net/view/1542" rel="nofollow noreferrer">script</a>, and these are the results:</p>
  
  <p><img src="https://i.stack.imgur.com/LdSuY.png" alt="enter image description here"></p>
  
  <p>Besides, the distribution of numbers is:</p>
  
  <p><img src="https://i.stack.imgur.com/S0CVF.png" alt="enter image description here"></p>
  
  <p>Thus, the implementation of <em>@Luis Mendo</em> is the one that scales better for low <code>L</code> values, which is my case. But, <em>@Rody Oldenhuis</em> optimized proposal is fast interdependently of the <code>L</code> value. Hence, a combined solution could be:</p>
  
  <pre><code>function mat = assignPermMatrix_comb(M,N,L,K)
      R = M*N;
      mat = zeros([L R]);
      if L&lt;K*0.15
          ind = true(1,R); 
          while R
              mat(:,ind) = randi(K, L, R); 
              ind = any(diff(sort(mat))==0);
              R = nnz(ind);
          end
      else
          for ii=1:R
              mat(:,ii) = randperm(K,L);
          end
      end
      mat = reshape(mat.', [M N L]);
  end
  </code></pre>
  
  <p>I am very thankful for all the effort that you put in your answers.</p>