Extract fixed length arrays from each row of a matrix and build new matrix made of them
2 views (last 30 days)
Show older comments
Yusuke Kadowaki
on 13 Nov 2017
Commented: Andrei Bobrov
on 13 Nov 2017
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.
0 Comments
Accepted Answer
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
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)');
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!