Save double in txt with specific scientific notation format using writecell

17 vues (au cours des 30 derniers jours)
Marcelo Filipchuk
Marcelo Filipchuk le 16 Fév 2022
I have a matrix with values in this format:
-4.33826930446975
-4.50867616174965
and I need them written in a *.txt file with this specific notation:
1.305911E-0002
1.101303E-0002
  7 commentaires
Marcelo Filipchuk
Marcelo Filipchuk le 20 Fév 2022
In that case I need the output to be zero.
Jan
Jan le 21 Fév 2022
What have you tried so far and which problems occur? You can use sprintf('%E') and check, if the exponent have 2 or 3 digits. Then replace 'E+' by 'E+0' or 'E+00' (or with '-') accordingly. Alternatively determine the exponent manually using log(abs(x)) and print it and the mantissa using sprintf.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 21 Fév 2022
You probably should be more specific about the rounding or truncation you want to have done for additional digits after the 6th decimal point, paying attention to negatives and to which way '5' should go.
format long g
A = -4.33826930446975
A =
-4.33826930446975
B = 0.013059114373
B =
0.013059114373
fmt(A)
ans = '-4.338269E+0000'
fmt(B)
ans = '1.305911E-0002'
fmt(nan)
ans = '0.000000E+0000'
fmt(-inf)
ans = '0.000000E+0000'
function output = fmt(X)
if X == 0 || ~isfinite(X)
output = '0.000000E+0000';
return
end
D = floor(log10(abs(X)));
S = X./10.^D;
output = sprintf('%.6fE%+05d', S, D);
end

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by