Could someone explain how this code works?

1 visualización (últimos 30 días)
IBM watson
IBM watson el 23 de Oct. de 2018
Comentada: Torsten el 24 de Oct. de 2018
S=[1 3 0 2 0 0];
C=[0 2];
[~,col] = ismember(C,S);
S(col) = [];
S =
1 3 0 0
This code is for : exclude C from S with repetition while keeping the same order of elements in S.
But how it works?
[~,col] = ismember(C,S);

Respuesta aceptada

Guillaume
Guillaume el 23 de Oct. de 2018
Editada: Guillaume el 23 de Oct. de 2018
I'm not sure what there is to explain. As documented, col tells you where each element corresponding element of C is found in S. If the element of C is found in more than one position, you'll get the first one of these.
The code is also flawed and will error if any element of C is not found at all in S. The safe version of the code would be:
S = [1 3 0 2 0 0];
C = [0 2 4]; %note that the original code would error because 4 is not present is S
[found, where] = ismember(C, S);
S(where(found)) = [] %this will not error
  4 comentarios
IBM watson
IBM watson el 23 de Oct. de 2018
Many thanks to you!
Torsten
Torsten el 24 de Oct. de 2018
Note that the code from above assumes that the elements in C are distinct.
So setting
S=[1 3 0 2 0 0];
C=[0 0 2];
will not produce
S=[1 3 0]
but also
S=[1 3 0 0]
Best wishes
Torsten.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical 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