How to print using fprintf to distinguisish 1.1 from 1.10 and 1.100
2 views (last 30 days)
Show older comments
I am working on producing tributary pixels input file to GAMS and I need them to be numbered in a way that distinguishes 1.1 from 1.10 and 1.100. Is there a way to print a string of characters distinguishing these differences?
The way I would like my txt file to be displayed is:
1.1,0
.
.
1.10,1,1.9
a=num2str(tribarray(k).pixel,precision);
fprintf(fid, '%s, %s, %s\n', a, num2str(size(tribarray(k).trib,2))); %,num2str(tribarray(k).trib));
%fprintf(fid, '%s, %s, %s\n', tribarray(k).pixel, size(tribarray(k).trib,2));
for j = 1:size(tribarray(k).trib,2)
b=num2str(tribarray(k).trib(j));
fprintf(fid, '%s,', b);
end
Thanks, Mariam
0 Comments
Accepted Answer
Guillaume
on 1 Dec 2014
Edited: Guillaume
on 1 Dec 2014
What do you mean distinguish? They're the exact same numbers:
a = 1.1;
b = 1.10;
isequal(a, b) %return true of course.
However many zeros you wrote at the end of the number initially is immediately lost as soon as you store the number into any numeric variable. Your options are thus:
1. store your numbers as string always, never as numeric even initially:
a = '1.1'
b = '1.10'
fprintf('%s, %s', a, b)
2. store your numbers as two integers, the integral part and the fractional part:
ai = 1; af = 1;
bi = 1; bf = 10;
fprintf('%d.%d, %d.%d', ai, af, bi, bf)
----
Side note: Don't do
fprintf('%s', num2str(anumber));
but
fprintf('%d', anumber) %for integers
fprintf('%f', anumber) %for real numbers
More Answers (2)
Kelly Kearney
on 1 Dec 2014
I would just do a simple concatenation, rather than try to figure out the proper %f precision for each:
[r,c] = meshgrid(1:108,1:102);
lbl = arrayfun(@(x,y) sprintf('%d.%d',x,y), r, c, 'uni', 0);
0 Comments
Mariam
on 1 Dec 2014
Edited: Mariam
on 1 Dec 2014
6 Comments
Stephen23
on 1 Dec 2014
Yes, I just noticed Kelly's answer: they also give an excellent solution which keeps the row and column data separate.
Guillaume
on 2 Dec 2014
To this I would add, that using a dot to separate the two coordinates may not be the wisest idea, since here it is not used to separate the integral and fractional parts of a number as is the norm but to separate coordinates. Any other symbol would be better (except comma which is used for the same purpose in some languages)
See Also
Categories
Find more on Graphics Object Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!