indexing groups of elements in a vector in a certain way

Hi all,
I have two vectors A and B where they look like the following:
%vector A
A = [1 1
4 1
5 1
6 1
5 2
6 2
7 2
3 3
4 3
5 3
3 3];
%vector B
B = [12 2
34 3
23 3
56 2
34 1
54 1
14 3
76 2
45 1
76 1
65 1];
The second column of each of these vectors corresponds to the index of each row. As can be seen, vector A has 3 main "groups". For each of these groups, there are 2 groups that corrspond to them in vector B. For example, for group 1 in vector A there are two groups 2 and 3 in vector B, and so on do forth.
It can be seen that in total vector B has 6 main groups. And here where I need help!
I want to reindex the rows of vector B without changing its elements order so that it contains 6 gorups and looks like:
%vector C
C = [12 1
34 2
23 2
56 1
34 3
54 3
14 4
76 5
45 6
76 6
65 6];
In this way, group 1 in vector A, has groups 1 and 2 in the new vector C. Group 2 in vectorA has groups 3 and 4 in vectro C. Group 3 in vector A has groups 5 and 6 in vector C.
Any help would be appreicted.
Thanks.

 Respuesta aceptada

%matrix A
A = [1 1
4 1
5 1
6 1
5 2
6 2
7 2
3 3
4 3
5 3
3 3];
%matrix B
B = [12 2
34 3
23 3
56 2
34 1
54 1
14 3
76 2
45 1
76 1
65 1];
[~,~,idx] = unique([A(:,2),B(:,2)],'rows','stable');
%matrix C
C = [B(:,1) idx];
disp(C)
12 1 34 2 23 2 56 1 34 3 54 3 14 4 76 5 45 6 76 6 65 6

2 comentarios

LH
LH el 23 de Jul. de 2024
thanks, that's great!
Voss
Voss el 23 de Jul. de 2024
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

LH
el 23 de Jul. de 2024

Comentada:

el 23 de Jul. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by