Problem with using `reshape` to reorder the matrix.
2 次查看(过去 30 天)
显示 更早的评论
I am trying to reorder my matrix "by block" in columns.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/333801/image.png)
See the code below, it is a mini case of my problem. It only has 2 "blocks"(In the graph above, it has 3).
a = [1,7,4,10;
2,8,5,11;
3,9,6,12];
output = [a(:,[1,2]);a(:,[3,4])];
I think this way is not very delicate. I think I should use the combination of transpose and reshape. If it is impossible, I would like to know either.
0 个评论
回答(2 个)
julian navas
2020-7-19
编辑:julian navas
2020-7-19
I think I don't get 100% your question but from the shape of 'output' see if this is what you need
a(:,[2,3])=a(:,[3,2])
reshape(a,[],2)
ans =
1 7
2 8
3 9
4 10
5 11
6 12
0 个评论
Image Analyst
2020-7-19
编辑:Image Analyst
2020-7-19
Did you just try a dumb for loop?
m = reshape(1:63, 3, 21)
[rowsm, columnsm] = size(m)
outputColumns = 7 % Columns to "lock"
numGroups = columnsm / outputColumns;
outputRows = rowsm * numGroups
m2 = zeros(outputRows, outputColumns);
row = 1;
for col = 1 : numGroups
col1 = (col-1) * outputColumns + 1;
col2 = col1 + outputColumns - 1;
m2(row:row+rowsm-1,:) = m(:, col1:col2);
row = row + rowsm;
end
m2
In my example I started with a 3x21 matrix and used 7 columns for a groups, so the output has 7 columns and (21/7) * 3 = 9 rows.
m =
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61
2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63
m2 =
1 4 7 10 13 16 19
2 5 8 11 14 17 20
3 6 9 12 15 18 21
22 25 28 31 34 37 40
23 26 29 32 35 38 41
24 27 30 33 36 39 42
43 46 49 52 55 58 61
44 47 50 53 56 59 62
45 48 51 54 57 60 63
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!