Reverse filling a array in MATLAB

2 Ansichten (letzte 30 Tage)
ML_Analyst
ML_Analyst am 21 Jun. 2022
Kommentiert: Voss am 21 Jun. 2022
Hello
I have a 1*3000 double variable in my workspace which looks like below:
array_1 = [NaN,NaN,NaN,NaN,NaN,340,133,133,133,NaN,NaN,NaN,145,NaN,NaN,NaN,NaN,78,68,89,NaN,NaN,NaN ........]
What i need is if there is a numerical value and NaN after that, then that numerical value is to be copied to all NaN elements, untill next numerical value is hit. For example, in the above array_1, 133 numerical value is there and a NaN follows this, so here the value 133 should be copied to all NaN till 145 is reached, then again since next value to 145 is NaN, again 145 is copied to next NaN till 78 is reached. Like this i want to do my for my entire array.
Output should be like below (highlighted modified indexes):
array_1 = [NaN,NaN,NaN,NaN,NaN,340,133,133,133,133,133,133,145,145,145,145,145,78,68,89,89,89,89 ........]
Here is what i have tried, i am not sure if there is an effficient way than this:
I have considered "a" as my array.
Start_value = 0;
Start_Idx=1;
for i =1:(numel(a)-1)
if ~isnan(a(i))
if isnan(a(i+1))
Start_Idx = i+1;
Start_value = a(i);
end
else
if ~isnan(a(i+1))
End_Idx = i;
a(Start_Idx:End_Idx) = Start_value;
end
end
end
Any help would be apprreciated.

Akzeptierte Antwort

Voss
Voss am 21 Jun. 2022
array_1 = [NaN,NaN,NaN,NaN,NaN,340,133,133,133,NaN,NaN,NaN,145,NaN,NaN,NaN,NaN,78,68,89,NaN,NaN,NaN]
array_1 = 1×23
NaN NaN NaN NaN NaN 340 133 133 133 NaN NaN NaN 145 NaN NaN NaN NaN 78 68 89 NaN NaN NaN
array_1 = fillmissing(array_1,'previous')
array_1 = 1×23
NaN NaN NaN NaN NaN 340 133 133 133 133 133 133 145 145 145 145 145 78 68 89 89 89 89

Weitere Antworten (0)

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by