Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading zero in Matlab's scientific notation

In Matlab, when printing using e such as fprintf('%10.5e\n', pi/100) one will get the result to be 3.14159e-02. However, what if I want the number to have a leading zero such as 0.314159e-1? How can I manage this with Matlab?

The reason I ask is that I am trying to print to a file which I need to have leading zeros. Otherwise, I would not care.

Thanks.

like image 440
drjrm3 Avatar asked May 08 '13 23:05

drjrm3


People also ask

What is a leading zero in scientific notation?

A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation.

How to represent scientific notation in MATLAB?

Scientific notation For example, 1,400,000 can be written as 1.4 x 106. In MATLAB (and other programming languages) a convenient shorthand for this is 1.4e6.

How do you change notation in MATLAB?

Select MATLAB > Command Window, and then choose a Numeric format option. The following table summarizes the numeric output format options. Short, fixed-decimal format with 4 digits after the decimal point.

How do I get rid of E in MATLAB?

you can use "format short g" command in the start of the code. I am a fresher in matlab but as far as i know it can help to get rid of e in the answer.


2 Answers

I don't think there is any clever way to do it:

your_number = pi;
['0.' strrep(sprintf('%10.5e',your_number*10), '.', '')]

>> ans =

0.314159e+01
like image 60
Franck Dernoncourt Avatar answered Sep 29 '22 10:09

Franck Dernoncourt


my solution is pretty crude but this is just to illustrate. You can do it yourself with a small function that will look for the relevant strings in the number, trim it after e, add 0. in the beginning and increse by 1 the exponent at the end, for example:

function b=fooo(a)
b=a;
k1 = strfind(a, '.');
k2 = strfind(a, 'e-');
suffix=num2str(str2num(b(k2+1:k2+3))+1);
b(k2+1:end)=[];
b(k1)=[];
b=['0.' b suffix];

where an input like

ans=fooo(sprintf('%10.5e\n', pi/100))

will yield the answer:

ans =
   0.314159e-1
like image 33
bla Avatar answered Sep 29 '22 10:09

bla