Reversing a part of matrix
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Bartosz Bagrowski
el 29 de Abr. de 2022
Comentada: Star Strider
el 30 de Abr. de 2022
Hey, I would like to choose two random values in a matrix and reverse from the first random number to the second one.
i=randsample(10,2)
i1=i(1);
i2=i(2);
let's say we got two random numbers - 3 and 7
M=[10 20 30 40 50 60 70 80 90 100];
I would like to get the matrix as following:
M_new=[10 20 70 60 50 40 30 80 90 100];
Could anyone help me to code it?
The method with the flip doesn't help much.
0 comentarios
Respuesta aceptada
Star Strider
el 29 de Abr. de 2022
A few examples of a robust approach —
M=[10 20 30 40 50 60 70 80 90 100];
i=sort(randsample(10,2))
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
i=sort(randsample(10,2))
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
i=sort(randsample(10,2))
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
i=sort(randsample(10,2))
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
i=sort(randsample(10,2))
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
.
2 comentarios
Star Strider
el 30 de Abr. de 2022
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.
Más respuestas (3)
Voss
el 29 de Abr. de 2022
i=sort(randsample(10,2)) % sort so that i(2) >= i(1)
i1=i(1);
i2=i(2);
M=[10 20 30 40 50 60 70 80 90 100];
M_new = M;
M_new(i1:i2) = M(i2:-1:i1)
0 comentarios
Riccardo Scorretti
el 29 de Abr. de 2022
A possible way is to pass through an vector of index (= ind in the code hereafter):
M=[10 20 30 40 50 60 70 80 90 100];
t = randsample(10, 2) % I reserve i for the imaginary unit
ind = 1 : 10;
ind(t) = t([2 1]);
M = M(ind)
0 comentarios
Riccardo Scorretti
el 29 de Abr. de 2022
Another way (more efficient, I think) is to do a swp by hand:
M=[10 20 30 40 50 60 70 80 90 100];
t = randsample(10, 2) % I reserve i for the imaginary unit
tmp_ = M(t(1)) ; M(t(1)) = M(t(2)) ; M(t(2)) = tmp_
1 comentario
Voss
el 29 de Abr. de 2022
@Riccardo Scorretti Note that these answers swap the two elements at indices t, but the question asks to reverse the order of all elements between those indices.
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices 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!