Extract fixed length arrays from each row of a matrix and build new matrix made of them

2 views (last 30 days)
I want to extract fixed length arrays from each row of a matrix and build a new matrix made of them. For example, I want to make matrix B from matrix A as follows.
A = magic(4);
B = [a(1,1:3); a(2,2:4); a(3,1:3); a(4,2:4)];
It's complicated so I expected matlab to move like this
b = a(:,[1:3;2:4;1:3;2:4]);
As you know, it doesn't work. But I feel like there's a simple grammar to do this. So if you know that, I'd like you to share that with me. Thanks.

Accepted Answer

Walter Roberson
Walter Roberson on 13 Nov 2017
There is no simple grammar for this. It is usually easiest and clearest to do it with a loop.
It is also possible to do this by using carefully using sub2ind, or to do the calculations equivalent to sub2ind.
idx = [1:3;2:4;1:3;2:4];
B = A( bsxfun(@plus, (1:size(A,1)).', (idx-1) * size(A,1)) );
However, I do not recommend this code. It might be efficient but it is also obscure. You will probably find yourself having to reinvent the proper combination of operations every time.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 13 Nov 2017
Edited: Andrei Bobrov on 13 Nov 2017
for MATLAB >= R2016b
[m,n] = size(A);
B = A(m*((0:n-2) + rem((1:n)-1,2)') + (1:m)');
  2 Comments
Yusuke Kadowaki
Yusuke Kadowaki on 13 Nov 2017
How could you come up with that? So impressive and beautiful. However what I meant is doing this with arbitrary chosen index like the Walter's answer. Sorry that I confused you. I really appreciate your answer. I learned a lot from it.

Sign in to comment.

Categories

Find more on 初等数学 in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!