How to cut an array and reshape it while keeping the content in order?
Show older comments
I have an array similar to what's below. How do I cut and move it so that after the 11th column (were it begins to go to 1 again) so that it's a 10x11 matrix instead of 5x22?
The reshape function doesn't work as it keeps the 1st column, pushes the 2nd column down and below the 1st column, keeps the 3rd column, and pushes the 4th column below the 2nd column. It messes up the data. Basically I want to cut the latter half of the data from column 12:end and place it below the 1:11 columns.
(5x22) T1 =
1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0
(10x11)T1 =
1 1 1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
Accepted Answer
More Answers (3)
This code can easily be changed to split the matrix into two, three, or more blocks. It assumes that the number of columns is divisible by this number of blocks.
>> blk = 2;
>> tmp = reshape(T1,size(T1,1),[],blk);
>> reshape(permute(tmp,[1,3,2]),[],size(tmp,2))
ans =
1 1 1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 0 0 0
1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 0
Example
We first define a function:
function out = moveblock(mat,blk)
tmp = reshape(mat,size(mat,1),[],blk);
out = reshape(permute(tmp,[1,3,2]),[],size(tmp,2));
end
and test this on a matrix:
>> T = ones(3,1)*(1:12)
T =
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11 12
>> moveblock(T,2)
ans =
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
7 8 9 10 11 12
7 8 9 10 11 12
7 8 9 10 11 12
>> moveblock(T,3)
ans =
1 2 3 4
1 2 3 4
1 2 3 4
5 6 7 8
5 6 7 8
5 6 7 8
9 10 11 12
9 10 11 12
9 10 11 12
>> moveblock(T,4)
ans =
1 2 3
1 2 3
1 2 3
4 5 6
4 5 6
4 5 6
7 8 9
7 8 9
7 8 9
10 11 12
10 11 12
10 11 12
Jos (10584)
on 6 Jul 2016
This is easy using a cell array as an intermediate step
T = repmat(1:12,3,1) % example array
S = size(T)
n = 3
if mod(S(2),n)>0
C = mat2cell(T, S(1), repmat(S(2)/n,1,n))
Tout = cat(1,C{:})
else
disp('Not possible.')
Tout = []
end
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!