precision of string conversion using string()

20 views (last 30 days)
Cristian Berceanu on 31 Oct 2023
Edited: Dyuman Joshi on 31 Oct 2023
I used to do numeric to string conversion using compose, but I recently found out how easy it is to use just string(a). Nevertheless, I came across some precision issues when using it. See below, why is "pi" being converted with different precision in the various cases below?
Regards,
Cristian
>> string([pi])
ans = "3.1416"
>> string([pi 1])
ans =
1×2 string array
"3.1416" "1"
>> string([pi 100])
ans =
1×2 string array
"3.14159" "100"
>> string([pi 127])
ans =
1×2 string array
"3.141593" "127"
>> string([pi 15000])
ans =
1×2 string array
"3.14159265" "15000"

Rik on 31 Oct 2023
Let's first replicate what you show:
my_fun([],@string)
my_fun([pi])
ans = "3.1416"
my_fun([pi 1])
ans = 1×2 string array
"3.1416" "1"
my_fun([pi 100])
ans = 1×2 string array
"3.14159" "100"
my_fun([pi 127])
ans = 1×2 string array
"3.141593" "127"
my_fun([pi 15000])
ans = 1×2 string array
"3.14159265" "15000"
The answer seems to be that this is the standard behaviour for num2str. So this is not unique to string. It does make sense that the precision for pi is increased if you add more precision for the other values in the array.
my_fun([],@num2str)
my_fun([pi])
ans = '3.1416'
my_fun([pi 1])
ans = '3.1416 1'
my_fun([pi 100])
ans = '3.141593 100'
my_fun([pi 127])
ans = '3.141593 127'
my_fun([pi 15000])
ans = '3.14159265 15000'
function my_fun(data,set_fun)
persistent fun
if nargin==2,fun=set_fun;return,end
feval(fun,data)
end
Cristian Berceanu on 31 Oct 2023
I guess I am going back to compose then...

Dyuman Joshi on 31 Oct 2023
Edited: Dyuman Joshi on 31 Oct 2023
From the documentation of string, subsection - Input arguments :- Input Type - Numeric array
"Output format and precision equivalent to using num2str. Use compose to specify more precise formatting.
If A is empty, [], the output is a 0-by-0 empty string array.
Use char to convert to ASCII or Unicode points."
For a numeric array, the behaviour of string() is equivalent to that of num2str().
Now, the documentation of num2str does not specify why the output is such when a precision is not provided. It just mentions - "The output format depends on the magnitudes of the original values."
The precision for each numeric value when converting to text via string (and equivalently num2str) is determined by various parameters. You can get more information about this by checking out the code for num2str().
type num2str.m

Categories

Find more on Characters and Strings in Help Center and File Exchange

R2023b

Community Treasure Hunt

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

Start Hunting!