How to extract last non-zero element above current row in same column?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Genaro Hiscock
el 22 de Mayo de 2020
Comentada: Genaro Hiscock
el 23 de Mayo de 2020
Hi everyone,
I'm dealing with a column of quarterly data (shares outstanding in an equities dataset) and need to fill in NaN or 0 elements with the last non-zero entry in a row above in the same column (provided the security is the same - I've got a loop that checks this condition first).
Loops quickly become inefficient for the missing data filling task if i need to check each prior row sequentially. The number of empty cells above is typically two, but it can be quite irregular...could be six, could be more. I don't think 'find' works for this particular task either, but I'm quite new to coding so could be wrong.
I'm sure there must be a very simple solution. Any suggestions?
Best,
Gerry
0 comentarios
Respuesta aceptada
Abdolkarim Mohammadi
el 22 de Mayo de 2020
I think the best way is find as you mentioned.
for i1 = 1:numel(X)
if any ([isnan(X(i1)); X(i1)==0])
idx = find (X(1:i1-1),1,'last');
X(i1) = X(idx);
end
end
2 comentarios
Más respuestas (1)
Ameer Hamza
el 22 de Mayo de 2020
Try fillmissing(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/fillmissing.html
fillmissing(A, 'previous') % A is your matrix
Ver también
Categorías
Más información sobre Performance and Memory en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!