using fprintf to print same length values

How can I use fprintf to print values with the same length (the number of digits after the pointer is changing based on the number of digits before the pointer)?
0.00000000
30.0000248
360.000305

Antworten (2)

Azzi Abdelmalek
Azzi Abdelmalek am 30 Dez. 2013
Bearbeitet: Azzi Abdelmalek am 30 Dez. 2013

0 Stimmen

b=360.000305
m=9 % fixed length
out=sprintf('%9.9f',b)
ii=numel(strfind(out,'.'))
out=out(1:m+ii)

8 Kommentare

Image Analyst
Image Analyst am 30 Dez. 2013
What is a?
Never mind. I figured it out and corrected it:
b=[0.00000000
30.0000248
360.000305
12345.678]
m=9; % fixed length
for k = 1 : length(b)
out=sprintf('%9.9f',b(k));
ii=numel(strfind(out,'.'));
out=out(1:m+ii);
fprintf('%s\n', out);
end
Nice clever solution.
Ronaldo
Ronaldo am 30 Dez. 2013
Azzi:
I would appreciate it if you finalize the answer and then I will accept this answer.
Azzi Abdelmalek
Azzi Abdelmalek am 30 Dez. 2013
Ronaldo, Analyst has corrected the answer, in my answer a should be out. Look at edited answer
Ronaldo
Ronaldo am 30 Dez. 2013
Bearbeitet: Azzi Abdelmalek am 30 Dez. 2013
Azzi, This looks more organized. Please replace it with the current one.
b=[0.00000000
30.0000248
360.000305
12345.678]
m=9; % fixed length
for k = 1 : length(b)
out=sprintf('%9.9f',b(k));
ii=numel(strfind(out,'.'));
out=out(1:m+ii);
fprintf('%s\n', out);
end
Azzi Abdelmalek
Azzi Abdelmalek am 30 Dez. 2013
This works fine, what is the problem?
Ronaldo
Ronaldo am 31 Dez. 2013
Please add the following line (for the sake of completeness). I will accept the answer. Thanks for your great help.
fprintf('%s\n', out);
Azzi Abdelmalek
Azzi Abdelmalek am 31 Dez. 2013
Ronaldo, I am not adding anything.

Melden Sie sich an, um zu kommentieren.

Daniel
Daniel am 1 Sep. 2017
Bearbeitet: Daniel am 1 Sep. 2017

0 Stimmen

b=360.000305
m=9 % fixed length
out=sprintf('%9.9f',b)
ii=numel(strfind(out,'.'))
out=out(1:m+ii)
% Azzi's got no time for correctness
fprintf('%s\n', out)

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 30 Dez. 2013

Bearbeitet:

am 1 Sep. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by