How can I insert rows of NaN into a vector of discontinuous values

5 views (last 30 days)
Hey guys
Working with some data which have a ton of gaps; what I want to do is expand the data matrix into the size of a reference vector, filling NaN's along the way.
The first column in my data matrix represents dates. I want to insert rows of NaN's where the dates are missing. So if datavec represents the first column in my data and refvec represents what it should look like, I would like the output matrix' first column to look like newvec.
datavec = [1992 1994 1995 1996 2000] refvec = [1992 1993 1994 1995 1996 1997 1998 1999 2000]
newvec = [1992 NaN 1994 1995 1996 NaN NaN NaN 2000]
I've tried combinations of the insertrows.m file on the exchange and a few other options, all of which failed miserably
Cheers!

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 9 Apr 2014
datavec = [1992 1994 1995 1996 2000]
refvec = [1992 1993 1994 1995 1996 1997 1998 1999 2000]
newvec = nan(size(refvec))
newvec(ismember(refvec,datavec))=datavec
  6 Comments
Aakash
Aakash on 9 Apr 2014
Awesome, thanks!
The intuition as I see it is, fill a matrix with NaN, to be replaced later on. We then find where our actual dates match our reference dates. Then replace those values, leaving you with nothing but NaNs.
anas ibnu
anas ibnu on 20 Feb 2019
hi i have a similar issue as yours .. and i tried the above (lastone) code and it gives an error "Subscripted assignment dimension mismatch."
can you please say what does it means .thanks in advance

Sign in to comment.


Alfredo guerrero
Alfredo guerrero on 4 Dec 2017
Edited: Alfredo guerrero on 4 Dec 2017
Hi Guys I am new in Matlab.
I have two different variables in size, how can i fill with NaN var2 in order to have the same length I mean I need the result in var2 = [2;4;3;2;1;4;5;4;NaN;NaN;NaN;NaN;NaN;NaN;NaN]
%% Real DATA
var1 = [1;2;3;4;5;6;7;8;9;10;11;12;13;14;15];
var2 = [2;4;3;2;1;4;5;4]
I hope someone help me!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!