7 views (last 30 days)

Show older comments

Ameer Hamza
on 30 Mar 2020

Edited: Ameer Hamza
on 30 Mar 2020

Try this:

x = [1;2;3;4;nan;nan;nan;nan;nan;5;7;8;nan;nan;nan;nan;11;11;12;nan;nan;nan;15];

bb = regionprops(isnan(x));

idx_nnan = find(~isnan(x));

idx_nan = find(isnan(x));

[~,idx] = min(abs(idx_nan - idx_nnan'), [], 2);

x(idx_nan) = x(idx_nnan(idx));

a = [bb.Centroid];

a(1:2:end) = [];

bb = bb(a==fix(a));

for i=1:numel(bb)

idx_center = bb(i).Centroid(2);

idx = cumsum(bb(i).BoundingBox([2 4])) + [-0.5 0.5];

x(idx_center) = mean(x(idx));

end

Original x:

x =

1

2

3

4

NaN

NaN

NaN

NaN

NaN

5

7

8

NaN

NaN

NaN

NaN

11

11

12

NaN

NaN

NaN

15

New x:

x =

1.0000

2.0000

3.0000

4.0000

4.0000 % <--- nearesr value

4.0000 % <--- nearesr value

4.5000 % average

5.0000 % <--- nearesr value

5.0000 % <--- nearesr value

5.0000

7.0000

8.0000

8.0000 % <--- nearesr value

8.0000 % <--- nearesr value

11.0000 % <--- nearesr value

11.0000 % <--- nearesr value

11.0000

11.0000

12.0000

12.0000 % <--- nearesr value

13.5000 % average

15.0000 % <--- nearesr value

15.0000

darova
on 30 Mar 2020

Use bwlabel

A1 = isnan(A); % find NaN

[L,n] = bwlabel(A1); % label each region

xx = 1:length(A);

for i = 1:n % loop through each region

BW = L==i; % select region

if sum(BW(:))>1 % if more than one 'NaN'

ix1 = find(BW,1,'first'); % first index of region

ix2 = floor(mean(BW.*xx)); % find mean index in region

ix3 = find(B2,1,'last'); % last index of region

A(ix1:ix2) = A(ix1-1); % fill first part

A(ix2+1:ix3) = A(ix3+1); % fill second part

else

ix = find(BW);

A(ix) = mean(A(ix([-1 1]))); % average

end

end

Andrei Bobrov
on 31 Mar 2020

x = [1;2;3;4;nan;nan;nan;nan;nan;5;7;8;nan;nan;nan;nan;11;11;12;nan;nan;nan;15];

out = [x,f1(x)]

x = [16.3;nan(15,1);14.8];

out = [x, f1(x)]

Here f1:

function out = f1(x)

b1 = fillmissing(x,'linear');

b2 = fillmissing(x,'nearest');

d = [0;diff(bwdist(~isnan(x)),2);0]==-2;

out = b2;

out(d) = b1(d);

end

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

Start Hunting!