Reversing a part of matrix

7 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2022-4-29
A few examples of a robust approach —
M=[10 20 30 40 50 60 70 80 90 100];
i=sort(randsample(10,2))
i = 2×1
5 6
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
M_new = 1×10
10 20 30 40 60 50 70 80 90 100
i=sort(randsample(10,2))
i = 2×1
3 9
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
M_new = 1×10
10 20 90 80 70 60 50 40 30 100
i=sort(randsample(10,2))
i = 2×1
1 9
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
M_new = 1×10
90 80 70 60 50 40 30 20 10 100
i=sort(randsample(10,2))
i = 2×1
2 7
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
M_new = 1×10
10 70 60 50 40 30 20 80 90 100
i=sort(randsample(10,2))
i = 2×1
8 9
M_new = [M(1:i(1)-1) flip(M(i(1):i(2))) M(i(2)+1:end)]
M_new = 1×10
10 20 30 40 50 60 70 90 80 100
.
  2 个评论
Bartosz Bagrowski
Bartosz Bagrowski 2022-4-30
Thank you very much for helping me to solve the problem!
Star Strider
Star Strider 2022-4-30
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

请先登录,再进行评论。

更多回答(3 个)

Voss
Voss 2022-4-29
i=sort(randsample(10,2)) % sort so that i(2) >= i(1)
i = 2×1
3 7
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)
M_new = 1×10
10 20 70 60 50 40 30 80 90 100

Riccardo Scorretti
Riccardo Scorretti 2022-4-29
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
t = 2×1
8 10
ind = 1 : 10;
ind(t) = t([2 1]);
M = M(ind)
M = 1×10
10 20 30 40 50 60 70 100 90 80

Riccardo Scorretti
Riccardo Scorretti 2022-4-29
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
t = 2×1
1 10
tmp_ = M(t(1)) ; M(t(1)) = M(t(2)) ; M(t(2)) = tmp_
M = 1×10
100 20 30 40 50 60 70 80 90 10
  1 个评论
Voss
Voss 2022-4-29
@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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by