sprintf
Format data into string
Syntax
str = sprintf(format, A, ...)
[str, errmsg] = sprintf(format, A, ...)
Description
str = sprintf(format, A, ...) applies the format to all elements of array A and any additional array arguments in column order, and returns the results to string str.
[str, errmsg] = sprintf(format, A, ...) returns an error message string when the operation is unsuccessful. Otherwise, errmsg is empty.
Input Arguments
Examples
Example 1
Format floating-point numbers:
sprintf('%0.5f',1/eps) % 4503599627370496.00000
sprintf('%0.5g',1/eps) % 4.5036e+15
Example 2
Explicitly convert double-precision values to integers:
sprintf('%d',round(pi)) % 3
Example 3
Combine literal text with array values:
sprintf('The array is %dx%d.',2,3) % The array is 2x3
Example 4
On a Windows system, convert PC-style exponential notation (three digits in the exponent) to UNIX style notation (two digits):
a = sprintf('%e', 12345.678);
if ispc
a = strrep(a, 'e+0', 'e+');
end
Example 5
This example demonstrates the use of the width field of a format specifier to set the minimum width of the result. This is different from the sscanf function where this field represents the maximum width of the result.
The first statement uses a format of %6d, which is equal to the number of digits in the input value. sprintf returns a single value as the result:
N = sprintf('%6d', [123456])
N =
123456
The second statement passes a format specifier of %025d, in which the width field of 25 determines the minimum width of the return value:
N = sprintf('%025d', [123456])
N =
0000000000000000000123456
The 0 in the %025d format specifier indicates that you want leading zeros to be shown in the output.
Input Arguments
| fileID | One ofthe following:
Default: 1 (the screen) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| format | String in single quotation marks that describes the format ofthe output fields. Can include combinations of the following:
Conversion characters and optional operators appear in the followingorder (includes spaces for clarity):
The following table lists the available conversion charactersand subtypes.
|
本文深入解析了sprintf函数的用法,包括如何将数据格式化为字符串、输入参数、输出结果以及常见例子。通过实际操作演示,帮助读者掌握sprintf函数的基本应用。

1348

被折叠的 条评论
为什么被折叠?



