MATLAB: How count NaN values and replace NaNs in a sequence with that number nanvector I have a vector [0 0 NaN 0 0 NaN NaN NaN 0 0 0 0 0 NaN] and I want [0 0 1 0 0 3 3 3 0 0 0 0 0 1]. Is it possible without a for cycle? Best Answer I don't think it's entirely possible to do it without a loop, but the loop can be limited to the number of sequences (3 steps in your example)v = [0 0 NaN 0 0 NaN NaN NaN 0 0 0 0 0 NaN];seqedges = find(diff([false, isnan(v), false]));seqstarts = seqedges(1:2:end);seqends = seqedges(2:2:end);seqlengths = seqends - seqstarts;for seq = 1:numel(seqstarts) v(seqstarts(seq):seqends(seq)-1) = seqlengths(seq);endedit: actually, it's possible without a loop:v = [0 0 NaN 0 0 NaN NaN NaN 0 0 0 0 0 NaN];nanlocs = isnan(v);seqedges = find(diff([false, nanlocs, false]));seqlengths = seqedges(2:2:end) - seqedges(1:2:end);v(nanlocs) = repelem(seqlengths, seqlengths) Related SolutionsMATLAB: How to find the sequences with length bigger than n in a vector v = [1 2 3 4 5 6 7 10 12 16 17 18 19 20 21 24 25 30 31 32 33 34 35 36]minlength = 6;isconsecutive = diff(v ) == 1;seqedges = find(diff([false, isconsecutive, false]));seqstarts = seqedges(1:2:end);seqstops = seqedges(2:2:end);seqlengths = seqstops - seqstarts + 1;tokeep = seqlengths >= minlengthindicestokeep = cell2mat(arrayfun(@(s, e) s:e, seqstarts(tokeep), seqstops(tokeep), 'UniformOutput', false);filteredv = v(indicestokeep) MATLAB: Does a cell vector contains only NaN cisnan = @(C)all(cellfun(@(x)all(isnan(x(:))),C));cisnan(your_cell) Related QuestionFinding values of specific range from table row or columnFinding the start and end indices of 3 or more repeating 0’s.Replace numbers in a matrix that are surrounded in 8-directions by NaNs to NaNsHelp with removing duplicate sub-elements….
Best Answer