9969

# Rearranging an array using for loop in Matlab

Question:

## I'm going to show you three methods. One where you need to have a `for` loop, and two others when you don't:

Method #1 - `for` loop

## First, create a matrix that is 3 x 5, then keep track of an index that will go through your array. After, create a double `for` loop that will help you populate the array.```index = 1; array = 1 : 15; %// Array we wish to access matrix = zeros(3,5); %// Initialize for m = 1 : 3 for n = 1 : 5 matrix(m,n) = array(index); index = index + 1; end end matrix = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ```

Method #2 - Without a `for` loop

## Simply put, use `reshape`:```matrix = reshape(1:15, 5, 3).'; matrix = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ````reshape` will take a vector and restructure it into a matrix so that you populate the matrix by columns first. As such, we want to put 1 to 5 in the first column, 6 to 10 in the second and 11 to 15 in the third column. Therefore, our output matrix is in fact 5 x 3. When you see this, this is actually the <strong>transposed</strong> version of the matrix we want, which is why you do `.'` to transpose the matrix back.

Method #3 - Another method without a `for` loop (tip of the hat goes to Luis Mendo)