Question

I have a matrix of dimensions (4000x4) (lets call this A) that contains data which is plotted on the y axis. I also have a separate matrix that is (4000,1) (lets call this B) that contains data plotted on the x axis. When plotted this produces 4 separate line graphs one for each column.

In matrix A there are many Nan (not a number) values in every column. I want to replace the Nan values with interpolated values. I have written a code that does this but it issues a warning. This is the code that I have written.

A(:,:)=interp1(B,A,B(:,1),'cubic');

When I run this code a warning is issued due to the data not being evenly spaced. Also this code is quite slow. This code is quite slow for the job. I want to modify the code so that no warning is issued and only values that are Nan are interpolated rather than interpolating every values (as this code does). I need to do this to speed up the code.

Thanks

Was it helpful?

Solution

I assume you just have NaN's in your data vector A and your x-axis vector B is alright?

For example take a equidistant time vector t from 1 to 100. And a data vector x where every tenth value is NaN:

% example data
t = 1:100;
x = 100*t-t.^2;
x(10:10:end) = NaN;

Now take all values of t and x which are not NaN as sample points and interpolate them with the complete time-vector t as query points.

xi = interp1( t(~isnan(x)), x(~isnan(x)) , t, 'cubic');

or a little more complex for your case:

% example data
B = (1:4000)';                 % 4000x1 double
A = repmat(1000*B-B.^2,4,1)';  % 4000x4 double
A(randi(400,40,1)) = NaN;      % random NaNs in your data matrix

Ai = zeros(size(A));
for ii = 1:size(A,2);
    tmp = A(:,ii);
    Ai(:,ii) = interp1( B(~isnan(tmp)) , tmp(~isnan(tmp)) , B, 'cubic');
end

and the loopless alternative:

C  = num2cell(A,1);
Ci = cellfun(@(x) interp1( B(~isnan(x)), x(~isnan(x)), B,'cubic'), C, ...   
             'UniformOutput',false);
Ci = cell2mat(Ci')';

OTHER TIPS

use the extrapolation option. here an example from matlab help

without extrapolation vq2 = interp1(x,v,xq,'linear') vq2 = NaN NaN 14 NaN NaN

with linear extrapolation vq3 = interp1(x,v,xq,'linear','extrap') vq3 = 8 10 14 4 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top