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

1 visualización (últimos 30 días)
BL
BL el 1 de Sept. de 2021
Comentada: BL el 1 de Sept. de 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 comentarios
KSSV
KSSV el 1 de Sept. de 2021
What are the elements of A and B? what is a1, b1 all these?
BL
BL el 1 de Sept. de 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.

Iniciar sesión para comentar.

Respuestas (1)

Walter Roberson
Walter Roberson el 1 de Sept. de 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

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by