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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by