Extend vector with NaN at specific points
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Owen Gray
am 29 Jan. 2021
Kommentiert: Owen Gray
am 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!
0 Kommentare
Akzeptierte Antwort
Daniel Catton
am 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];
%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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!