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

Generate a 3-d matrix from a vector in Matlab

Ray Phan
Jul 02, 2015
<p>Here's one approach with <a href="http://www.mathworks.com/help/matlab/ref/kron.html" rel="nofollow"><code>kron</code></a> and <a href="http://www.mathworks.com/help/matlab/ref/reshape.html" rel="nofollow"><code>reshape</code></a>:</p> <pre><code>A = 0:N-2; B = reshape(kron(A, ones(M, N-1)), M, N-1, []); </code></pre> <p>We use <code>kron</code> to produce <code>M x (N-1)</code> 2D matrices that are stacked for as many elements as there are in <code>A</code> and each matrix is multiplied by the corresponding value in <code>A</code>. The next step is to take each of the concatenated 2D matrices and place them as individual slices in the third dimension, done by <code>reshape</code>.</p> <h1>Example with <code>M = 5, N = 4</code></h1> <pre><code>&gt;&gt; B B(:,:,1) = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 B(:,:,2) = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 B(:,:,3) = 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31056004/Generate%20a%203-d%20matrix%20from%20a%20vector%20in%20Matlab/31056339">Stack Overflow</a>.</p>
comments powered by Disqus