Can I find set of values in larger set in one step?

Hi,
I am working on a code that takes a very long time to implement, so I try to optimize it
If I look for a set of values (x) in a larger set (z), can I do that in a way faster than using for and find?
x=[1 2 3];
z=[10 2 1 5 7 .....];
thanks

10 Commenti

ismember() with two outputs
ismember is almost certainly the way to go, as @Walter Roberson says. A more specific answer could be given, if you tell us more specifically what output you want from the inputs x and z.
For example are there multiple copies of the values, and is what you are looking for as output a cell array, one entry for each item in x, giving the indices in z ?
Thanks,
In current problem there are no copies of the values,and the output shoud be in this example 2 and 3, in other word their positions.
But if there are copies of the values, are there function to do that?
huda nawaf
huda nawaf il 15 Ago 2022
Modificato: huda nawaf il 15 Ago 2022
thanks @Walter Roberson, but there is a problem when removing their positions
x=[1 2 3];
z=[10 2 1 5 7];
[r r1] =ismember(x,z); the output is :
r = 1 1 0
r1 = 3 2 0
r1=r1(r1~=0);
z(z==z(r1 ))=[ ]
why this error:
Arrays have incompatible sizes for this operation.
the output should
z=[10 5 7]
x=[1 2 3];
z=[10 2 1 5 7];
z(ismember(z,x)) = []
z = 1×3
10 5 7
If Bruno's method solves the problem, this works also:
x = [1 2 3];
z = [10 2 1 5 7];
z = setdiff(z, x, 'stable')
z = 1×3
10 5 7
what if I have c ,when I find 1 and 2 in z , I want to remove it from c
x=[1 2 3];
>> z=[10 2 1 5 7];
>> c=[9 4 2 1];
I need the output is
c=[9 4]
x=[1 2 3];
z=[10 2 1 5 7];
c=[9 4 2 1];
c(ismember(c,intersect(z,x)))=[]
c = 1×2
9 4

Accedi per commentare.

 Risposta accettata

As per my understanding, you want to look for the set of values in x in another larger set, z in an optimized way.
The following functions can help you achieve this:
  • The intersect function returns common values between x and z in sorted order:
>> x=[1 2 3];
>> z=[10 2 1 5 7 4 6 9];
>> intersect(x,z)
ans =
1 2
For more information regarding the intersect function, refer to the following documentation link:
  • The ismember function returns an array containing logical 1 (true) where the data in A is found in B.
>> ismember(x,z)
ans =
1×3 logical array
1 1 0
For more information regarding the ismember function, refer to the following documentation link:

Più risposte (0)

Prodotti

Release

R2022a

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by