PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 17, 2022

[FIXED] How to use interp1 with NaN values?

 July 17, 2022     matlab, matrix, nan, performance, warnings     No comments   

Issue

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


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')';


Answered By - Robert Seifert
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing