How to interchange entries of a n array?

2 次查看(过去 30 天)
X = [ 4 2 3 6 5 1 ];
x1 = [2 3 1 2];
The following code integange entries of X based on x1
Xnew = X ;
for ii = 1:numel(x1 )
Xnew([ii x1(ii)]) = Xnew([x1(ii) ii ]);
end
Xnew
1- Is there any other faster way to do that?

采纳的回答

Walter Roberson
Walter Roberson 2022-3-28
编辑:Walter Roberson 2022-3-29
1- Is there any other faster way to do that?
There are potentially overlaps: a row might get moved in and moved out again. Therefore the changes must be applied in sequence. The only real improvement would be to calculate the full interchange table first, and then shuffle the rows only once.
Mathematically it could be modeled by a series of permutation matrices, like
[1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1]
that all got multiplied together to build the final matrix. If you had a number of different X matrices all to be reordered according to the same pattern it just might be worth building that kind of permutation matrix, but it isn't worth it for one X.

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by