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

1 vue (au cours des 30 derniers jours)
BL
BL le 1 Sep 2021
Commenté : BL le 1 Sep 2021
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 commentaires
KSSV
KSSV le 1 Sep 2021
What are the elements of A and B? what is a1, b1 all these?
BL
BL le 1 Sep 2021
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.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 1 Sep 2021
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

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by