필터 지우기
필터 지우기

Extend vector with NaN at specific points

조회 수: 8 (최근 30일)
Owen Gray
Owen Gray 2021년 1월 29일
댓글: Owen Gray 2021년 1월 29일
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
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.
  댓글 수: 1
Owen Gray
Owen Gray 2021년 1월 29일
This is great thank you so much!!! Really appreciate it and makes sense cheers, worked perfectly

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by