Which rows of a 2-column array contain elements of 1-column array.
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
When I look for the elements of 1-column array, a, inside a 2-column array, b, I would like to know which rows of b contain the elements of a.
By using ismember:
[~,i2] = ismember(a,b)
the index i2 indicates the position of the elements of a inside b, as b was a 1-column array, instead of a 2-column array. How can I know in which rows of b I can find the elements of a ?
% here my example:
a = [ 6208
2920
6630
725
7069
434
4334
8343
2935
2920
6976
3202
2920
1409
4842
3545
8079
3908
5663
5333
3495
6142
6866
6361
5402
5731
5743
2331
8083
6866
8158
7537
5198
8003
3514
6752
4618
2577
1637
7026
6842
1409
921
7208
6866
7778
8600
3571
4439
8003
4288
7244
8656
6519
7262
4619
8478
5504
1227
1778
8872
1447
5027
6614
7243
2639];
b = [ 5446 7487
2321 2930
5446 7026
5333 5783
4446 5333
523 1227
6231 7026
822 6349
822 8478
4439 4921
5611 8343
2331 8810
5333 6231
523 6614
4446 7208
8083 8343
6231 8478
6691 8656
4446 5783
8083 8656
6543 7208
3363 5446
741 1301
6614 6842
2331 5783
1095 6842
2321 8478
4439 5333
5611 6349
741 5783
822 2321
1227 6349
2930 7026];
[~,i2] = ismember(a,b)
% desired output (I would like to know the rows of "b" that contain the elements of "a")
b(i2(i2~=0),:)
Index in position 1 exceeds array bounds. Index must not exceed 33.
% eventually, I would like to compare "a(find(i2))" with "b(i2(i2~=0),:)"
0 Commenti
Risposta accettata
Voss
il 3 Dic 2022
Modificato: Voss
il 3 Dic 2022
ismember returns linear indices as its second output. You can use ind2sub to convert to row + column indices.
a = [ 6208
2920
6630
725
7069
434
4334
8343
2935
2920
6976
3202
2920
1409
4842
3545
8079
3908
5663
5333
3495
6142
6866
6361
5402
5731
5743
2331
8083
6866
8158
7537
5198
8003
3514
6752
4618
2577
1637
7026
6842
1409
921
7208
6866
7778
8600
3571
4439
8003
4288
7244
8656
6519
7262
4619
8478
5504
1227
1778
8872
1447
5027
6614
7243
2639];
b = [ 5446 7487
2321 2930
5446 7026
5333 5783
4446 5333
523 1227
6231 7026
822 6349
822 8478
4439 4921
5611 8343
2331 8810
5333 6231
523 6614
4446 7208
8083 8343
6231 8478
6691 8656
4446 5783
8083 8656
6543 7208
3363 5446
741 1301
6614 6842
2331 5783
1095 6842
2321 8478
4439 5333
5611 6349
741 5783
822 2321
1227 6349
2930 7026];
Notice that b has 33 rows, so for instance the element at linear index 44 is at row 11, column 2 (i.e., all 33 in the first column plus 11 more in the second column).
[~,i2] = ismember(a,b);
% optional: remove all the zeros from i2 (doesn't affect the final result, b(r(r~=0),:))
i2 = i2(i2 > 0)
[r,c] = ind2sub(size(b),i2)
b(r(r~=0),:)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!