Cutting (dividing) a matrix into a specific number of rows.
조회 수: 6 (최근 30일)
이전 댓글 표시
Hi, I have an exemplary matrix A(8,3) which contains 2 smaller matrices A1(4,3) and A2(4,3). I want to convert A into matrix B(12,2).
A=[11 12 13;21 22 23;31 32 33;41 42 43;51 52 53;61 62 63;71 72 73;81 82 83]
B=[11 51;21 61;31 71;41 81;12 52;22 62;32 72;42 82;13 53;23 63;33 73;43 83]
Are two for loops enough, or do I need more? How many to iterate to in each loop? I am trying to figure this out in many ways and still without success. Can I ask for help or at least a hint?
댓글 수: 0
답변 (2개)
Stephen23
2024년 3월 27일
A = [11,12,13;21,22,23;31,32,33;41,42,43;51,52,53;61,62,63;71,72,73;81,82,83];
B = reshape(permute(reshape(A,[],2,3),[1,3,2]),[],2)
댓글 수: 3
Stephen23
2024년 3월 27일
편집: Stephen23
2024년 3월 27일
"In reality, I will have thousands of such smaller matrices that I need to rearrange. The number of columns in A can also be larger. Will it work then, too?"
Yes, when you know and specify the correct number of columns, etc, and all submatrices have the same sizes, etc.
Nothing I have shown you is limited to two submatrices. That is rather the point of using this general approach.
"Why are there as many as 3 parameters in permute?"
PERMUTE supports exactly two inputs, so presumably you are actually asking about its 2nd argument, the dimension order. I specified three dimensions because that is how many dimensions the intermediate array has.
Alexander
2024년 3월 27일
Just another approach. Simple but it might be helpful. I assume in the first half of your matrix are x or t, in the second half y data (measured or simulated channel 1). So the code below is only for one channel, but I think it's easy to modify if more channels are needed.
clear;
%{
% Your matrix:
A = [11,12,13
21,22,23
31,32,33
41,42,43
51,52,53
61,62,63
71,72,73
81,82,83]
%}
% Just to construct flexible test matrices remove until the "A" if you trust the code below. If you don't
% trust the
Rows = 9; Cols = 4; nn = 1;
for (ii = 1:Rows)
for (jj = 1:Cols)
A(ii,jj) = nn;
nn = nn +1;
end
%nn = nn +1;
end
A
% Here begins the code you migth need.
[Rows,Cols]=size(A);
if(mod(Rows,2)); fprintf(2,'No. of rows must be even\n'); return; end
ll = numel(A)/2;
B = []; C = [];
for(ii = Rows/2:Rows/2:Rows-1)
for(jj = 1:Cols)
B = [B;A(1:ii,jj)];
C = [C;A(1+ii:ii*2,jj)];
end
end
% The matrix you want to have:
B = [B, C]
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!