filling the first NaN right after the last non NaN with a value that is half of the non NaN
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello there, could you help to make the following matrix p = [NaN 2 NaN; 2 4 NaN; 2 6 8; NaN 8 2; NaN NaN 1; NaN NaN 1] into p1 , which equals [NaN 2 NaN; 2 4 NaN; 2 6 8; 1 8 2; NaN 4 1; NaN NaN 1]...by filling the first NaN right after the last non NaN with a value that is half of the non NaN. Waiting for any answers from you . Thank you.
Best , Jessie
0 commentaires
Réponses (1)
Robert
le 30 Nov 2015
You can use the function isnan to find the appropriate values to replace as in the following code:
p = [
NaN 2 NaN;
2 4 NaN;
2 6 8;
NaN 8 2;
NaN NaN 1;
NaN NaN 1
];
p1 = p(1:end-1,:); % NaN replacement sources
p2 = p(2:end,:); % NaN replacement candidates
replace = isnan(p2) & ~isnan(p1);
p2(replace) = p1(replace)/2; % replace the NaN's that met your criteria
p2 = [p(1,:);p2]; % put back the first row, which never changes
disp(p2)
This code yields your expected result for your example. I am not completely certain what you expect to happen for NaN's with preceding values that aren't the last in the column. If you want to leave those as NaN and not replace them, you will need an additional step. After creating the logical indices variable, replace, use the following code to keep only the last true value in each column.
replace = replace & flipud(cumsum(flipud(replace)))==1;
You can use this test value to see the difference in the two interpretations.
p = [
NaN 2 NaN;
2 4 NaN;
2 6 8;
NaN 8 NaN;
NaN NaN 2;
NaN NaN NaN
];
0 commentaires
Voir également
Catégories
En savoir plus sur NaNs dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!