precision of string conversion using string()
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Cristian Berceanu
il 31 Ott 2023
Modificato: Dyuman Joshi
il 31 Ott 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"
0 Commenti
Risposta accettata
Rik
il 31 Ott 2023
Let's first replicate what you show:
my_fun([],@string)
my_fun([pi])
my_fun([pi 1])
my_fun([pi 100])
my_fun([pi 127])
my_fun([pi 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])
my_fun([pi 1])
my_fun([pi 100])
my_fun([pi 127])
my_fun([pi 15000])
function my_fun(data,set_fun)
persistent fun
if nargin==2,fun=set_fun;return,end
feval(fun,data)
end
Più risposte (1)
Dyuman Joshi
il 31 Ott 2023
Modificato: Dyuman Joshi
il 31 Ott 2023
"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.
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
0 Commenti
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!