How do I print the common elements in a row vector?

1 visualización (últimos 30 días)
Yasmin Touly
Yasmin Touly el 13 de Abr. de 2018
Respondida: Stephen23 el 13 de Abr. de 2018
If I have two-row vectors,
A = [3, 11, 7]
B = [11, 2, 5]
and I have to find the common element, how do I do that?
C = ismember(A, B)
But, using the ismember() function will only give me values in 0 or 1. I want to print out '11', but how do I accomplish that? Do i use the function unique()? any help would be very much appreciated.thank u.

Respuestas (2)

David Fletcher
David Fletcher el 13 de Abr. de 2018
Editada: David Fletcher el 13 de Abr. de 2018
use the logical vector to index the common values
common=A(ismember(A,B))
if you have multiple values in A that are the same you will get
A = [3, 11, 7 11 3]
B = [11, 2, 5]
common=A(ismember(A,B)))
common =
11 11
You can use unique to filter the list
common=unique(A(ismember(A,B)))
common =
11

Stephen23
Stephen23 el 13 de Abr. de 2018
The simplest solution is to use intersect:
>> intersect(A,B)
ans = 11

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