Rearrange element in vector

Suppose i have

v1 = { x1, x2, x3, x4, x5, x6 }

v2 = { x5,x3,x1}

How to rearrange V2 according to position in V1 so that

v3 = { x1,x3,x5}

 

 

3 Answers



0



There may be a better way to accomplish this, but you can:

v1 = { x1, x2, x3, x4, x5 };
v2 = { x5, x3, x1 };

//Get the index of each element of v2's location in v1
idx = indcv(v2, v1);

//Sort the indices
idx = sortc(idx, 1);

//Assign v3
v3 = v1[idx];

This code will assign 'v3' to be:

x1
x3
x5

You could accomplish the same action for numeric data by using the function indnv instead of indcv.

aptech

1,773


0



what if i want v4 to be

x1

.

x3

.

x5

 



0



//Make v4 a missing value
v4 = miss(0,0);

//Reshape v4 into a 5x1 vector of missing values
v4 = reshape(v4, 5, 1);

//Use the same idx from the problem above
v4[idx] = v1[idx];

Then the print statement:

print $v4;

will return:

X1 
. 
X3 
. 
X5 
`

For reference, below is the complete code snippet for both parts:

v1 = { x1, x2, x3, x4, x5 };
v2 = { x5, x3, x1 };

idx = indcv(v2, v1);

//Sort the indices
idx = sortc(idx, 1);

//Assign v3
v3 = v1[idx];

//Make v4 a missing value
v4 = miss(0,0);

//Reshape v4 into a 5x1 vector of missing values
v4 = reshape(v4, 5, 1);

v4[idx] = v1[idx];

aptech

1,773

Your Answer

3 Answers

0

There may be a better way to accomplish this, but you can:

v1 = { x1, x2, x3, x4, x5 };
v2 = { x5, x3, x1 };

//Get the index of each element of v2's location in v1
idx = indcv(v2, v1);

//Sort the indices
idx = sortc(idx, 1);

//Assign v3
v3 = v1[idx];

This code will assign 'v3' to be:

x1
x3
x5

You could accomplish the same action for numeric data by using the function indnv instead of indcv.

0

what if i want v4 to be

x1

.

x3

.

x5

 

0
//Make v4 a missing value
v4 = miss(0,0);

//Reshape v4 into a 5x1 vector of missing values
v4 = reshape(v4, 5, 1);

//Use the same idx from the problem above
v4[idx] = v1[idx];

Then the print statement:

print $v4;

will return:

X1 
. 
X3 
. 
X5 
`

For reference, below is the complete code snippet for both parts:

v1 = { x1, x2, x3, x4, x5 };
v2 = { x5, x3, x1 };

idx = indcv(v2, v1);

//Sort the indices
idx = sortc(idx, 1);

//Assign v3
v3 = v1[idx];

//Make v4 a missing value
v4 = miss(0,0);

//Reshape v4 into a 5x1 vector of missing values
v4 = reshape(v4, 5, 1);

v4[idx] = v1[idx];

You must login to post answers.

Have a Specific Question?

Get a real answer from a real person

Need Support?

Get help from our friendly experts.