How do remove a subset of elements from a double array in Matlab? The arrays are ordered and 1-dimensional.
For example, given
A=[1,3,5,6,7];
a=[3,6];
desire
A_a=[1,5,7];
If a
was scalar, I can do A_a=A(A~=a)
. How does it work if a
is not scalar?
My concern with naïve looping around A_a=A(A~=a(i))
is that, seemingly, for every element a(i)
, a comparison is made for every element in A
, which ignores the underlying order in the 2 arrays.
CodePudding user response:
Here are several ways to do this:
1. Using ismember
to create logical indexing:
A_a = A(~ismember(A, a))
2. Treat A and a as sets, and use setdiff
A_a = setdiff(A, a)
3. Use arrayfun
to generate logical indices
A_a = A(arrayfun(@(x)~any(x==a), A))
4. Good old fashioned for loop
A_a = []
for element = A
if ~any(a == element )
A_a(end 1) = element ;
end
end