views:

400

answers:

1

Say I have the following matrix:

A = randi(10, [6 3])
     7    10     3
     5     5     7
    10     5     1
     6     5    10
     4     9     1
     4    10     1

And I would like to extract each 2 rows and put them into the third dimension, so the result would be like:

B(:,:,1) =
     7    10     3
     5     5     7
B(:,:,2) =
    10     5     1
     6     5    10
B(:,:,3) =
     4     9     1
     4    10     1

I can obviously do this with a for loop, just wondering how to do it more elegantly as one-liner using permute/reshape/.. (note matrix size and step must be parameters)

% params
step = 5;
r = 15;
c = 3;

% data
A = randi(10, [r c]);
B = zeros(step, c, r/step); % assuming step evenly divides r

% fill
counter = 1;
for i=1:step:r
    B(:,:,counter) = A(i:i+step-1, :);
    counter = counter + 1;
end
+4  A: 

Here's a one-line solution using RESHAPE and PERMUTE:

C = 3;          % Number of columns
R = 6;          % Number of rows
newR = 2;       % New number of rows
A = randi(10,[R C]);  % 6-by-3 array of random integers
B = permute(reshape(A',[C newR R/newR]),[2 1 3]);

This of course requires that newR divides evenly into R.

gnovice
Exactly what I needed, thanks!BTW how can you index a matrix in row-major instead of column-major (the way MATLAB does) ?
Amro
Linear indexing of MATLAB matrix elements always follows column-major order. If you want to access elements along rows, you have to first transpose the matrix before performing linear indexing. That's why I have `A'` as the first argument to RESHAPE in the above solution. For more info on matrix indexing in MATLAB, check this link: http://www.mathworks.com/company/newsletters/digest/sept01/matrix.html
gnovice

related questions