Say I have a variable:
X = [NaN, NaN, 2, 5, 1, 6, NaN, 1, NaN NaN];
I need to remove/trim NaNs only when they occur at the edges, either at the beginning or the end, so X would be:
X = [2, 5, 1, 6, NaN, 1];
where the NaN occurring at the middle was untouched. I wrote some codes that work, but I think the codes could be much simpler (I tend to overcomplicate my codes ๐Ÿ˜…). Please suggest a simpler way to do this. Thanks!
NaNGroups = regionprops(isnan(X), 'Area').Area;
if isnan(X(1))
X(1:NaNGroups(1)) = [];
end
if isnan(X(end))
X(end-NaNGroups(end)+1:end) = [];
end

 ์ฑ„ํƒ๋œ ๋‹ต๋ณ€

KSSV
KSSV 2021๋…„ 1์›” 11์ผ

0 ๊ฐœ ์ถ”์ฒœ

X = [NaN, NaN, 2, 5, 1, 6, NaN, 1, NaN, NaN];
A = isnan(X) ;
idx = find(A & diff([0 A]) == 1 & diff([A 0]) == 0) ;
idx = [idx(1) idx(1)+1 idx(end) idx(end)+1] ;
X(idx) =[]
Also you can use:
find(isnan(X),2,'first')
find(isnan(X),2,'last')

๋Œ“๊ธ€ ์ˆ˜: 1

Adib Yusof
Adib Yusof 2021๋…„ 1์›” 12์ผ
Thank you so much!

๋Œ“๊ธ€์„ ๋‹ฌ๋ ค๋ฉด ๋กœ๊ทธ์ธํ•˜์‹ญ์‹œ์˜ค.

์ถ”๊ฐ€ ๋‹ต๋ณ€ (0๊ฐœ)

์นดํ…Œ๊ณ ๋ฆฌ

๋„์›€๋ง ์„ผํ„ฐ ๋ฐ File Exchange์—์„œ Logical์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ธฐ

์ œํ’ˆ

๋ฆด๋ฆฌ์Šค

R2020b

ํƒœ๊ทธ

์งˆ๋ฌธ:

2021๋…„ 1์›” 11์ผ

๋Œ“๊ธ€:

2021๋…„ 1์›” 12์ผ

Community Treasure Hunt

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

Start Hunting!

Translated by