Monday, July 27, 2009

Matlab: handling nan for findstr

In many situations handling NaNs can be tricky if we want to write vectorized code.

For example, if I have vector

x = [1 2 3 nan 5 6 nan nan 9 10 11 12 nan 14]


If I want to locate 2 consequtive NaNs, I may use a combination of find, isnan, and diff.

However, what if I want to locate a subvector that also contains NaN? For instance, how to find

y = [3 nan 5]


in x?

If y does not contain NaNs, we know we can use findstr.

The straitforward solution is to convert NaNs to some value that doesn't appear in y.

For example,

sudoNan = max(x)+1;
x(isnan(x)) = sudoNan;
y(isnan(y)) = sudoNan;
findstr(x,y)


An even easier method is:

xc = typecast(x,'uint64');
yc = typecast(y,'uint64');
findstr(xc,yc)

No comments: