Improving my forwardfill call
Mostrar comentarios más antiguos
I want to clean missing data by using the previous available data to fill gap and only a given gap length 'n' can be filled.
E.g. I have the following vector:
A = [0.1 0.2 0.3 NaN NaN NaN 0.7 NaN 0.9 1];
If n = 1
A_ffilled = [0.1 0.2 0.3 0.3 NaN NaN 0.7 0.7 0.9 1];
If n = 2
A_ffilled = [0.1 0.2 0.3 0.3 0.3 NaN 0.7 0.7 0.9 1];
So, this is exactly what is done in the fillmissing help page example:
function y = forwardfill(xs,ts,tq,n)
y = NaN(1,numel(tq));
y(1:min(numel(tq),n)) = xs;
end
n = 2;
gapwindow = [10 0];
[F,TF] = fillmissing(A,@(xs,ts,tq) forwardfill(xs,ts,tq,n),gapwindow,SamplePoints=t);
So far so good. However, I am wondering if I am not missing something as what I am doing seems so basic. E.g. with python in pandas, one can simply use the .ffill() method and provides the desired value for limit. Therefore, I am wondering if there is nothing more simple that the example above if I do not what the apply a specific function but only to take the previous value.
Thanks in advance.
Respuestas (1)
A = [0.1 0.2 0.3 NaN NaN NaN 0.7 NaN 0.9 1]
A_ffilled = forwardfill(A,1)
A_ffilled = forwardfill(A,2)
EDIT:
function [B,I]=forwardfill(A,n)
[I,I0]=deal( 1:numel(A) );
I(ismissing(A))=nan;
I=min(movmax(I,[n,0]) , I0);
B=A(I);
end
% function B=forwardfill(A,n)
%
% B=min(A, movmax(A,[n,0]) );
%
% end
2 comentarios
frlby
el 4 de Sept. de 2026 a las 9:35
Here's a version that fixes the ordering problem you mentioned, and also works for strings.
A = [0.1 0.2 0.1 NaN NaN NaN 0.7 NaN 0.9 1]
A_ffilled = forwardfill(A,2)
A_ffilled = forwardfill(string(A),2)
function [B,I]=forwardfill(A,n)
[I,I0]=deal( 1:numel(A) );
I(ismissing(A))=nan;
I=min(movmax(I,[n,0]) , I0);
B=A(I);
end
Categorías
Más información sobre Time Series Events en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!