Difference of two cells of row arrays in Matlab

I have an array of cells like

a={'potential'; 'impact'; 'of'; 'stranded'; 'assets'; 'and'; 'other'; 'necessary'; 'regulatory'; 'approvals'; 'assets'} 

and you want to subtract from it an array like b = {'a'; 'and'; "ABOUT"; "My"; '#'}.

Using setdiff (a, b) sorts my array after calculating the difference. I want to exclude from all elements present in b, without sorting a. It is also necessary to keep repetitions, for example. "assets" in array a should appear in two places in the final array.

The following code that I use performs the following task:

 for i = 1:length(b) tf = ~strcmp(b(i),a) a = a(tf,:) end 

But the problem is that the b array contains more than 200 string elements, which significantly slows down my code. Is there a better way to do this?

+4
source share
2 answers
 tf = ismember(a,b); a = a(~tf) 
+4
source
 EDU>> a a = 'potential' 'impact' 'of' 'stranded' 'assets' 'and' 'other' 'necessary' 'regulatory' 'approvals' 'assets' EDU>> b b = 'a' 'and' 'of' 'my' '#' [I,J]=setdiff(a,b); 

Now do

 EDU>> a(sort(J),:) ans = 'potential' 'impact' 'stranded' 'other' 'necessary' 'regulatory' 'approvals' 'assets' 
0
source

Source: https://habr.com/ru/post/1391158/


All Articles