Extract fixed length arrays from each row of a matrix and build new matrix made of them
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Yusuke Kadowaki
am 13 Nov. 2017
Kommentiert: Andrei Bobrov
am 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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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.
Weitere Antworten (1)
Andrei Bobrov
am 13 Nov. 2017
Bearbeitet: Andrei Bobrov
am 13 Nov. 2017
for MATLAB >= R2016b
[m,n] = size(A);
B = A(m*((0:n-2) + rem((1:n)-1,2)') + (1:m)');
2 Kommentare
Siehe auch
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!