Alesi Rowland
Alesi Rowland

Reputation: 441

Find smaller array within larger array

I have a data set composed of a vector of size ~1 000 000. I want to find the indices of where a fixed array is found (when 12 or more NaNs are found consecutively).

Most searches bring up ismember() or intersect() which do not do the job to my knowledge (would only return where any member of my search array of NaNs is).

I'm aware I could do this in a for loop, however, I have over 20 of these data sets and calculating all of these in this way would take a very long time.

If anyone has a time-inexpensive way of doing this, I would greatly appreciate it.

Upvotes: 0

Views: 208

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

You can use strfind for that. Although not documented, this function works for numeric vectors too:

>> x = [7 4 5 2 4 5];
>> y = [5 2 4];
>> strfind(x, y)
ans =
     3

However, it won't find NaN's. This is consistent with the fact that two NaN's are not equal to each other:

>> x = [7 4 NaN NaN NaN 5];
>> y = [NaN NaN NaN];
>> strfind(x, y)
ans =
     []

So if the pattern you want to find consists of NaN's you need to convert to a logical vector first:

>> x = [7 4 NaN NaN NaN 5];
>> y = [NaN NaN NaN];
>> xNaN = isnan(x);
>> yNaN = isnan(y);
>> strfind(xNaN, yNaN)
ans =
     3

Or in this case you can also use convolution:

>> find(conv(xNaN, yNaN, 'valid')==numel(yNaN))
ans =
     3

Upvotes: 3

Related Questions