Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Matlab equivalent to Python's `not in`?

Tags:

python

matlab

In Python, one could get elements that are exclusive to lst1 using:

lst1=['a','b','c']
lst2=['c','d','e']
lst3=[]
for i in lst1:
    if i not in lst2:
        lst3.append(i)

What would be the Matlab equivalent?

like image 974
CiaranWelsh Avatar asked Jan 13 '16 13:01

CiaranWelsh


People also ask

What is the equivalent of MATLAB in Python?

NumPy (Numerical Python)NumPy arrays are the equivalent to the basic array data structure in MATLAB. With NumPy arrays, you can do things like inner and outer products, transposition, and element-wise operations.

Does MATLAB replace Python?

Python can replace MATLAB Python is free and available on every platform and therefore is highly portable. Although Python was not intended as a free alternative to MATLAB, it's actually well suited for this role. Many people have successfully made the switch from MATLAB to Python.

Does MATLAB use Python?

MATLAB provides flexible, two-way integration with many programming languages, including Python. This allows different teams to work together and use MATLAB algorithms within production software and IT systems.

Is MATLAB better than Python?

MATLAB has very strong mathematical calculation ability, Python is difficult to do. Python has no matrix support, but the NumPy library can be achieved. MATLAB is particularly good at signal processing, image processing, in which Python is not strong, and performance is also much worse.


1 Answers

You are looking for MATLAB's setdiff -

setdiff(lst1,lst2)

Sample run -

>> lst1={'a','b','c'};
>> lst2={'c','d','e'};
>> setdiff(lst1,lst2)
ans = 
    'a'    'b'

Verify with Python run -

In [161]: lst1=['a','b','c']
     ...: lst2=['c','d','e']
     ...: lst3=[]
     ...: for i in lst1:
     ...:     if i not in lst2:
     ...:         lst3.append(i)
     ...:         

In [162]: lst3
Out[162]: ['a', 'b']

In fact, you have setdiff in Python's NumPy module as well, as numpy.setdiff1d. The equivalent implementation with it would be -

In [166]: import numpy as np

In [167]: np.setdiff1d(lst1,lst2) # Output as an array
Out[167]: 
array(['a', 'b'], 
      dtype='|S1')

In [168]: np.setdiff1d(lst1,lst2).tolist() # Output as list
Out[168]: ['a', 'b']
like image 128
Divakar Avatar answered Oct 26 '22 10:10

Divakar