2021年4月22日星期四

matlab array into "stacked" matrix

Is there a way to do the following?

I would like to turn a MATLAB array:

>> (1:10)'    ans =         1       2       3       4       5       6       7       8       9      10  

Into the following sequential matrix (I am not sure what is the name for this):

ans =       NaN   NaN   NaN     1     NaN   NaN   NaN     2     NaN   NaN   NaN     3       1     2     3     4       2     3     4     5       3     4     5     6       4     5     6     7       5     6     7     8       6     7     8     9       7     8     9    10  

I am able to do this, with the following function, but it iterates over each row and it is slow:

function V = vec2stack(X, num_sequences)        n = numel(X);    len_out = n - num_sequences + 1;    V = zeros(len_out,num_sequences);    for kk = 1:len_out      V(kk,:) = X(kk:kk +num_sequences - 1)';  end  V = [nan(num_sequences,num_sequences); V(1:end-1,:)];  end    X = 1:10;  AA = vec2stack(X,3)  

Running the above function for a vector of length 1,000,000 takes about 1 second, which is not fast enough for my purposes,

tic;  Lag = vec2stack(1:1000000,5);  toc;    Elapsed time is 1.217854 seconds.  
https://stackoverflow.com/questions/67222958/matlab-array-into-stacked-matrix April 23, 2021 at 09:49AM

没有评论:

发表评论