The output result of intersect function is not as the expected one

3 visualizaciones (últimos 30 días)
For example, when I run the following codes:
Cell1 = {'C';'B';'ZN';'FU';'PM';'A';'OI';'SR';'M';'TA';'AU';'P';'RU';'CU';'Y';'L';'AL';'CF';'WH'};
Cell2 = {'B';'ZN';'FU';'PM'};
[~,Index] = intersect(Cell1,Cell2);
The expected value of Index should be [2,3,4,5] However, when I run codes in MATLAB2014b,the results I have got is [2,4,5,3].
But, when I replace Cell1 and Cell2 as:
Cell1 = {'A','B','C','D'};
Cell2 = {'A','B'};
[~,Index] = intersect(Cell1,Cell2);
I got Index = [1,2],which is the same as the expected value.
So, weird. Hope someone can tell me what the cause of this problem.

Respuesta aceptada

Guillaume
Guillaume el 12 de Mzo. de 2015
By default, intersect sorts its output, and thus the indices returned correspond to that sorted order. You would have seen that had you asked for the intersection:
>>Cell1 = {'C';'B';'ZN';'FU';'PM';'A';'OI';'SR';'M';'TA';'AU';'P';'RU';'CU';'Y';'L';'AL';'CF';'WH'};
>>Cell2 = {'B';'ZN';'FU';'PM'};
>>[intersection ,Index] = intersect(Cell1,Cell2)
intersection =
'B'
'FU'
'PM'
'ZN'
Index =
2
4
5
3
If you want to keep the output in the same order as your first array, then use the stable option:
>>[intersection ,Index] = intersect(Cell1, Cell2, 'stable')
intersection =
'B'
'ZN'
'FU'
'PM'
Index =
2
3
4
5

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by