Subset matlab array with timestamps using another array that contains the timestamps to be deleted

StackOverflow https://stackoverflow.com/questions/23582759

  •  19-07-2023
  •  | 
  •  

Question

I've got a matlab array A with timestamps in the first column, and data in the second:

times = datenum('2014-05-10 12:00'):1/1440:datenum('2014-05-10 13:00');
data = rand(61,1);
A = [times' data];

I have another array B that contains the timestamps of the rows that should be deleted from array A:

B = [datenum('2014-05-10 12:10') datenum('2014-05-10 12:45')]';

How can I obtain an array that contains the data from array A without the data that have a timestamp listed in B? In reality, I'm working with a large dataset, so I'd rather not use (nested) loops.

Was it helpful?

Solution

One of several approaches,

C = A(~ismember(A(:,1),B),:);

Note that you need to be very careful when comparing floating point numbers for equality, and depending on how your dates have been created you might find that any direct comparison approach doesn't quite do what you expect.

E.g.

(0.3-(0.2+0.1))==0
ans =
      0

is correct to double precision, but often surprises people.

OTHER TIPS

I don't have a working matlab license on this machine to test a code example for you, but you can try the setdiff function before adding data to A. If that's not possible, use setdiff on C=A(1:end,1) and reassign A afterwards.

http://www.mathworks.de/de/help/matlab/ref/setdiff.html

Edit: here's a working code example:

[~,ia] = setdiff(A(:,1),B);
A_new = A(ia,:);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top