필터 지우기
필터 지우기

Swap all the values in a vector

조회 수: 29 (최근 30일)
Vasilis Chasiotis
Vasilis Chasiotis 2020년 4월 12일
I have the vector x=[1 2 3 4 5 6 7 8] and I want to create another one in which I have swaped the elements as (17)(24)(38)(56), that is the new vector is [7 4 8 2 6 5 1 3].
Note that I have lots of vectors in which the number 1,...,8 are in different positions. So, I need to make a connection between the numbers, that is for example (17)(24)(38)(56), but not between the positions of the numbers in the vectors.
Is there any function in Matlab so as to achieve it?
Thanks!

답변 (1개)

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020년 4월 12일
편집: Thiago Henrique Gomes Lobato 2020년 4월 12일
Yes, randperm:
rng(31415)
x=[ 1 2 3 4 5 6 7 8];
p = randperm(length(x));
xnew = x(p)
xnew =
7 8 1 2 6 4 5 3
If you want only the specific case of your given permutation, you can do it by indexing and it looks like this:
xnew = x([7 4 8 2 6 5 1 3])
ans =
7 4 8 2 6 5 1 3
  댓글 수: 2
Vasilis Chasiotis
Vasilis Chasiotis 2020년 4월 12일
편집: Vasilis Chasiotis 2020년 4월 12일
Your permutation is random, so it does not work.
For example in the vector x=[3 5 2 1 7 8 6 4], the desired output is [8 6 4 7 1 3 5 2].
So, I am asking about a function such that I connect numbers (17)(24)(38)(56) for each possible positions in the vectors.
Note that the numbers 1,...,8 are the elements of the vectors, not the positions of the vectors, and so
xnew = x([7 4 8 2 6 5 1 3])
does not work.
Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020년 4월 12일
Sorry, I misunderstood your question. This code does what you want:
xref=[ 1 2 3 4 5 6 7 8];
x=[3 5 2 1 7 8 6 4];
[xsort,sortedIndex] = sort(x);
RightOrder = sortedIndex([7 4 8 2 6 5 1 3]); % Indexing in sorted array, so always the same
xnew = x;
xnew(RightOrder) = xref
x =
8 6 4 7 1 3 5 2

댓글을 달려면 로그인하십시오.

카테고리

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