bru1987
bru1987

Reputation: 66

Reshaping MATLAB matrix in a particular way

I am working on a MATLAB code so that I can basically do this

enter image description here

To accomlish that, my code looks like this

A = [1:30]'; % Example matrix
rows = 3;

for i=1:(numel(A)-rows+1)
    B(1:rows,i)=A(i:i+rows-1,1);
end

Can someone help me do the same in a simpler way? I am guessing there is a one-line command that can solve that (maybe I'm wrong).

Upvotes: 3

Views: 124

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Let A and rows be defined as in your code. I'm assuming the values in A are just an example. If they are always 1, 2, ..., some of the solutions below can be simplified.

A = [1:30].';
rows = 3;

Here are some approaches:

  • My choice:

    B = A(bsxfun(@plus, (1:rows).', 0:numel(A)-rows));
    
  • An alternative:

    B = conv2(A.', flip(eye(rows)));
    B = B(:, rows:end-rows+1);
    
  • Slightly more inefficient:

    B = hankel(A);
    B = B(1:rows, 1:numel(A)-rows+1);
    
  • If you have the Image Processing Toolbox:

    B = im2col(A, [rows 1], 'sliding');
    

Upvotes: 2

Related Questions