control when to use exponential notation in num2str

10 vues (au cours des 30 derniers jours)
James Johnson
James Johnson le 3 Jan 2020
I would like to control when exponential notation is used vs when it is not for compact exponential notation in matlab.
For example.
num2str([0.0077;0.324;0.0000435],'%2.4G')
gives
' 0.0077'
' 0.324'
'4.35E-05'
but I want it to give
' 7.7E-03'
' 0.324'
'4.35E-05'
I'm aware of using the "E" notation to alway force exponential notation but I do not like the trailing zeros. I want to be able to specify that anything below 10^-2 should use compact exponential format. I suspect that it is an undocumented element of format spec.
Currently I have this nasty work around.
matlab_workaround=0.0077
if log10(matlab_workaround)<-2;
matlab_workaround=num2str(matlab_workaround,'%2.4E');
while contains(matlab_workaround,'0E')
matlab_workaround=strrep(matlab_workaround,'0E','E');
end
else
matlab_workaround=num2str(matlab_workaround,'%2.4G');
end

Réponses (1)

Walter Roberson
Walter Roberson le 3 Jan 2020
There is no control over conversion other than the format specification the way you are passing it in.
Note: num2str() uses sprintf() (or possibly sprintfc()), so it has the same restrictions that sprintf() has -- which is to say that it is not possible to customize the details of %g conversion.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by