Get each submatrix n columns longer than the column in the new matrix in Matlab

I am dealing with very large data sets (hundreds of thousands of columns, 14 rows), and I need each submatrix of n columns to be long, like a column in a new matrix, i.e.

1 3 5 7
2 4 6 8

becomes

1 3 5
2 4 6
3 5 7
4 6 8

when n = 2.

Now I have

n_data_points = size(data1, 1);
small_n = 60;
big_n = size(data1, 2);

new_2 = bsxfun(@(x,y)(data1(x + n_data_points * (y - 1))), (1:(n_data_points * small_n)).', 1:(big_n - small_n + 1));

But this method is rather slow. How to do this using your own Matlab actions?

EDIT

So, after the bench, noting some of the methods here and doing some more research, I settled on the following:

n = 60;
[m, big_n] = size(data1);
a = zeros((m*n), (big_n - n + 1));
for i = 1:(big_n - n + 1)
    a(:, i) = reshape(data1(:, i:(i + n - 1)), 1, m*n);
end 

This method takes about 2.3 seconds with a matrix of 14 by 387160, whereas my original method takes about 4.8, and @Divakar takes about 3.9.

+4
source share
2 answers

bsxfun, linear indexing -

[m1,n1] = size(data1)  %// Get size of input array data1
out = data1(bsxfun(@plus,[1:n*m1]',[0:n1-n]*m1))

-

data1 =
     9     2     8     2     4     9     4
     9     3     3     3     8     3     6
     5     8     9     6     6     7     1
     2     3     4     5     5     7     1
n =
     3
out =
     9     2     8     2     4
     9     3     3     3     8
     5     8     9     6     6
     2     3     4     5     5
     2     8     2     4     9
     3     3     3     8     3
     8     9     6     6     7
     3     4     5     5     7
     8     2     4     9     4
     3     3     8     3     6
     9     6     6     7     1
     4     5     5     7     1
+5

n = 2 :

new_data=[data1(:,1:end-1); data1(:,2:end)];

n > 2 ( , circshift, kron ..):

new_data=data1(:,1:end-n+1);
for k=2:n
  new_data=[new_data; data1(:,k:end-n+k)];
end

:

n=3;
data1 = randi(10,2,6)

 7     8     5     5     1     1
 8     2     9     2     7     4



new_data =

 7     8     5     5
 8     2     9     2
 8     5     5     1
 2     9     2     7
 5     5     1     1
 9     2     7     4
+1

All Articles