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?
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!