Question

I need to turn a large array into a matrix in the following way: to take the first m entries of the array and make that the 1st row of the matrix.

For example: if I had an array that was 100 entries long, the corresponding matrix would be 10 rows and each row would be 10 entries of the array with the order preserved.

I've tried the following code:

rows = 10
row_length = 10
a = randi(1,100);
x = zeros(rows,row_length)
for i=1:rows
    x(i) = a(i:i+row_length)
end

but with no luck. I'm stuck on how to slide the window along by row_length so that i will start from row_length+1 in the second (and subsequent) iterations of the loop.

Was it helpful?

Solution

The best way to do it is to use Matlab's reshape function:

reshape(a,row_length,[]).'

It will reshape by first assigning down the columns which is why I transpose at the end (i.e. .')

However just for the sake of your learning, this is how you could have done it your way:

rows = 10
row_length = 10
a = rand(1,100)
x = zeros(rows,row_length)
for i=1:row_length:rows*row_length             %// use two colons here, the number between them is the step size
    x(i:i+row_length-1) = a(i:i+row_length-1)  %// You need to assign to 10 elements on the left hand side as well!
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top