Extend vector with NaN at specific points
6 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Daniel Catton
2021-1-29
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];
%Define your vectors
[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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!