# Extend vector with NaN at specific points

28 views (last 30 days)
Owen Gray on 29 Jan 2021
Commented: Owen Gray on 29 Jan 2021
Hi there, I've got two vectors, RTdata(1x3120 double) and outcomeflat(1x3024). I basically want to add a NaN to the vector outcomeflat if there is one present in the same element in RTdataflat, AND if there is not already a NaN present at that positiion in outcomeflat. So e.g.
RTdataflat = [1 2 3 NaN 5 6 NaN 8 9 NaN]
outcomeflat = [3 4 7 NaN 9 2 8 9]
I'd want to convert outcomeflat to
outcomeflat = [3 4 7 NaN 9 2 NaN 8 9 NaN]
So far I tried to use this:
nan_locations = isnan(RTdataflat)
for n = 1:3120
if nan_locations(n) == 1
if outcomeflat(n) ~= NaN
b = NaN;
outcomeflat = cat(2, outcomeflat(1:n), b, outcomeflat(n:end));
end
end
end
However this outputs outcomeflat as a 1x3740 vector, as opposed to the 1x3120 vector that I need/expected. I'm not sure why the second if statement doesn't prevent this. I tried putting it in the same if statement using && however this produced the same result
Thanks!

Daniel Catton on 29 Jan 2021
I've been able to come up with this code, it follows my understanding of the problem given your example:
RTdataflat = [1 2 3 NaN 5 6 NaN 8 9 NaN];
outcomeflat = [3 4 7 NaN 9 2 8 9];
[Rx,Ry] = size(RTdataflat);
[ox,oy] = size(outcomeflat);
%Gets sizes of the vectors
q =Ry-oy;
outcomeflat(end+q) = 0;
%Pre-allocates some extra space in outcomeflat for the NaN variables
for b = 1:Ry
if isnan(RTdataflat(Rx,b))
if ~isnan(outcomeflat(Rx,b))
for c = flip(b:Ry)
outcomeflat(1,c) = outcomeflat(1,c-1); %Moves all data to allow space for NaN if data does not contain NaN already
end
end
outcomeflat(Rx,b) = NaN; %Adds NaN into the vector
end
end
%Returns the vector [3,4,7,NaN,9,2,NaN,8,9,NaN] as requested.
Owen Gray on 29 Jan 2021
This is great thank you so much!!! Really appreciate it and makes sense cheers, worked perfectly