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?
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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With