MATLAB: Find length NaN segments nan segments I have large vectors, containing quite a lot of NaN samples. I want to know the length of each array of NaNs within this vector, even when this equals 1. So I want to have the lenght of all NaN segments. Thanks in advance! Best Answer https://www.mathworks.com/matlabcentral/answers/444595-count-the-occurence-of-a-number-in-between-other-numbers - replace the first line with isnan(). Related SolutionsMATLAB: How to find the indices of NaN values in a cell array Try this: D = load('XTrain2_all.mat');XTrain2_all = D.XTrain2_all;hasNaN = cellfun(@nnz,cellfun(@isnan, XTrain2_all, 'Unif',0), 'Unif',0); % Cells With ‘NaN’ Valuesidx = find([hasNaN{:}]); % Their IndicesXTrain2_all(idx) = XTrain2_all(idx-1); % Replace With PrevioushasNaN = cellfun(@nnz,cellfun(@isnan, XTrain2_all, 'Unif',0), 'Unif',0); % CheckCheck = find([hasNaN{:}]); % Check. MATLAB: Count the occurence of a number in between other numbers This is simpler and actually works for all horizontal vectors (unlike the accepted answer):>> x = [ 1 0 0 1 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0];>> D = diff([false,x==0,false]);>> find(D<0)-find(D>0)ans = 2 1 5 1 1For a slightly faster version you can call find once:>> F = find(diff([false,x==0,false]));>> F(2:2:end)-F(1:2:end)ans = 2 1 5 1 1EDIT: uses Jan's logical vector suggestion. Related QuestionFilling nans between two valuesReplace an element of a vector by also redefining the vectorTrim only edge NaN valuesReplacing values from a separate vector to multiple repeated values in another vectorFilling the gaps in a vectorFinding values of specific range from table row or column
Best Answer