What is the best way to swap elements in an matrix ?

조회 수: 1 (최근 30일)
BL
BL 2021년 9월 1일
댓글: BL 2021년 9월 1일
Hi,
I wonder what is the best way to swap elements in a matrix without having to use "for" loop.
For example: I have an array like this
A = [ a1b1 a1b2 a1b3 a2b1 a2b2 a2b3 a3b1 a3b2 a3b3;
c1d1 c1d2 c1d3 c2d1 c2d2 c2d3 c3d1 c3d2 c3d3]
and I want to swap the elements such that it results in the following array
B = [ a1b1 a2b1 a3b1 a1b2 a2b2 a3b2 a1b3 a2b3 a3b3 ;
c1d1 c2d1 c3d1 c1d2 c2d2 c3d2 c1d3 c2d3 c3d3 ]
Thanks
BL
  댓글 수: 2
KSSV
KSSV 2021년 9월 1일
What are the elements of A and B? what is a1, b1 all these?
BL
BL 2021년 9월 1일
Hi,
I tried to formulate it in a general way. So a1b1 is just a number. E.g.
A = [ a1b1 a1b2 a1b3 a2b1 a2b2 a2b3 a3b1 a3b2 a3b3] = [11 12 13 21 22 23 31 32 33].
Just tried to show what is the desired swapping that I want to have.

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2021년 9월 1일
A = [
1121 1122 1123 1221 1222 1223 1321 1322 1323
3141 3142 3143 3241 3242 3243 3341 3342 3343
]
A = 2×9
1121 1122 1123 1221 1222 1223 1321 1322 1323 3141 3142 3143 3241 3242 3243 3341 3342 3343
B = [
1121 1221 1321 1122 1222 1322 1123 1223 1323
3141 3241 3341 3142 3242 3342 3143 3243 3343
]
B = 2×9
1121 1221 1321 1122 1222 1322 1123 1223 1323 3141 3241 3341 3142 3242 3342 3143 3243 3343
B2 = reshape(permute(reshape(A, 2, 3, 3),[1 3 2]), 2, [])
B2 = 2×9
1121 1221 1321 1122 1222 1322 1123 1223 1323 3141 3241 3341 3142 3242 3342 3143 3243 3343
B - B2
ans = 2×9
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by