Fprintf matlab что это
Описанные выше функции работы с файлами позволяют записывать и считывать информацию по байтам, которые затем требуется правильно интерпретировать для преобразования их в числа или строки. В то же время выходными результатами многих программ являются текстовые файлы, в которых явным образом записаны те или числа или текст. Например, при экспорте данных из MS Excel можно получить файл формата
174500,1.63820,1.63840,1.63660,1.63750,288
180000,1.63740,1.63950,1.63660,1.63820,361
181500,1.63830,1.63850,1.63680,1.63740,223
183000,1.63720,1.64030,1.63720,1.64020,220
где числа записаны в столбик и разделены запятой.
Прочитать такой файл побайтно, а затем интерпретировать полученные данные довольно трудоемкая задача, поэтому для этих целей были специально разработаны функции чтения
[value, count] = fscanf(fid, format, size)
count = fprintf(fid, format, a,b. )
таких данных в файл. Здесь value – результат считывания данных из файла; count – число прочитанных (записанных) данных; fid – указатель на файл; format – формат чтения (записи) данных; size – максимальное число считываемых данных; a,b. – переменные для записи в файл.
Приведем пример чтения данных из файла, приведенного выше с помощью функции fscanf():
S = fscanf(fid, ‘%d,%f,%f,%f,%f,%d’);
fclose(fid);
Здесь форматная строка состоит из спецификаторов
%d – работа с целочисленными значениями;
%f – работа с вещественными значениями
и записана в виде ‘%d,%f,%f,%f,%f,%d’. Это означает, что сначала должно быть прочитано целочисленное значение из файла, затем, через запятую должно читаться второе вещественное значение, затем третье и так далее до последнего целочисленного значения. Полный список возможных спецификаторов приведен в табл. 5.2.
В результате работы программы переменная S будет представлять собой вектор-столбец, состоящий из 24 элементов:
S = [174500 1,6382 1,6384 1,6366 1,6375 288 180000 1,6374 1,6395 1,6366 1,6382 361 181500 1,6383 1,6385 1,6368 1,6374 223 183000 1,6372 1,6403 1,6372 1,6402 220]’;
Несмотря на то, что данные были корректно считаны из файла, они из таблицы были преобразованы в вектор-столбец, что не соответствует исходному формату представления данных. Чтобы сохранить верный формат данных, функцию fscanf() в приведенном примере следует записать так:
S = fscanf(fid, ‘%d,%f,%f,%f,%f,%d’, [6 4]);
Тогда на выходе получится матрица S размером в 6 столбцов и 4 строки с соответствующими числовыми значениями.
Таблица 5.2. Список основных спецификаторов для функций fscanf() и fprintf()
Для записи данных в текстовый файл в заданном формате используется функция fprintf(). Ниже представлен пример записи матрицы чисел
180000 1.28210 1.28240 1.28100 1.28120 490
190000 1.28100 1.28150 1.27980 1.28070 444
200000 1.28050 1.28080 1.27980 1.28000 399
210000 1.27990 1.28020 1.27880 1.27970 408
220000 1.27980 1.28060 1.27880 1.28030 437
230000 1.28040 1.28170 1.28020 1.28130 419
000000 1.28140 1.28140 1.28010 1.28100 294
010000 1.28080 1.28190 1.28030 1.28180 458
020000 1.28190 1.28210 1.28080 1.28140 384
030000 1.28130 1.28170 1.28080 1.28140 313
в файл, в котором числовые значения должны разделяться точкой с запятой. Будем также предполагать, что данная матрица хранится в переменной Y.
Следует отметить, что в функции fprintf() переменная Y имеет знак транспонирования ‘, т.к. данные в файл записываются по столбцам матрицы. Кроме того, перед спецификаторами стоят числа, которые указывают сколько значащих цифр числа должно быть записано в файл. Например, спецификатор %6d говорит о том, что целые числа должны иметь 6 значащих цифр, а спецификатор %.4f означает, что после запятой будет отображено только 4 цифры. Наконец, в форматной строке были использованы управляющие символы
\r – возврат каретки;
\n – переход на новую строку
которые необходимы для формирования строк в выходном файле. В итоге, содержимое файла будет иметь вид:
180000;1.2821;1.2824;1.2810;1.2812;490
190000;1.2810;1.2815;1.2798;1.2807;444
200000;1.2805;1.2808;1.2798;1.2800;399
210000;1.2799;1.2802;1.2788;1.2797;408
220000;1.2798;1.2806;1.2788;1.2803;437
230000;1.2804;1.2817;1.2802;1.2813;419
0;1.2814;1.2814;1.2801;1.2810;294
10000;1.2808;1.2819;1.2803;1.2818;458
20000;1.2819;1.2821;1.2808;1.2814;384
30000;1.2813;1.2817;1.2808;1.2814;313
С помощью функции fprintf() можно записать значения двух и более переменных разного формата. Например, для записи числа и строки можно воспользоваться следующей записью:
str = ‘Hello’;
y = 10;
count = fprintf(fid, ‘%d\r\n%s\r\n’, y, str);
и содержимое файла будет иметь вид:
Таким образом можно осуществлять запись разнородных данных в файл в требуемом формате.
fprintf
Write data to text file
Syntax
Description
nbytes = fprintf( ___ ) returns the number of bytes that fprintf writes, using any of the input arguments in the preceding syntaxes.
Examples
Print Literal Text and Array Values
Print multiple numeric values and literal text to the screen.
%4.2f in the formatSpec input specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point. %8.3f in the formatSpec input specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point. \n is a control character that starts a new line.
Print Double-Precision Values as Integers
Explicitly convert double-precision values with fractions to integer values.
Write Tabular Data to Text File
MATLAB ® import functions, all UNIX ® applications, and Microsoft Word and WordPad recognize ‘\n’ as a newline indicator.
View the contents of the file with the type command.
Get Number of Bytes Written to File
Write data to a file and return the number of bytes written.
The fprintf function wrote 96 bytes to the file.
View the contents of the file with the type command.
Display Hyperlinks in Command Window
Display a hyperlink (The MathWorks Web Site) on the screen.
Input Arguments
fileID — File identifier
1 (default) | 2 | scalar
File identifier, specified as one of the following:
1 for standard output (the screen).
2 for standard error.
Data Types: double
formatSpec — Format of output fields
formatting operators
Format of the output fields, specified using formatting operators. formatSpec also can include ordinary text and special characters.
formatSpec can be a character vector in single quotes, or, starting in R2016b, a string scalar.
This table shows conversion characters to format numeric and character data as text.
Base 16 (hexadecimal), lowercase letters a – f
Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)
Exponential notation, such as 3.141593e+00 (Use a precision operator to specify the number of digits after the decimal point.)
Characters or strings
The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.
Note: If an input argument is an array, you cannot use identifiers to specify particular array elements from that input argument.
Always print a sign character (+ or –) for any numeric value.
Example: %+5.2f
Right-justify text.
Example: %+10s
Insert a space before the value.
Example: % 5.2f
Pad to field width with zeros before the value.
Example: %05.2f
Modify selected numeric conversions:
Minimum number of characters to print. The field width operator can be a number, or an asterisk ( * ) to refer to an input argument.
When you specify * as the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With * as the field width operator, you can print different values with different widths.
The function pads to field width with spaces before the value unless otherwise specified by flags.
Number of digits to the right of the decimal point
Example: ‘%.4f’ prints pi as ‘3.1416’
Number of significant digits
Example: ‘%.4g’ prints pi as ‘3.142’
The precision operator can be a number, or an asterisk ( * ) to refer to an argument.
When you specify * as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With * as the precision operator, you can print different values to different precisions.
When you specify *.* as field width and precision operators, you must specify field widths, precisions, and values as triplets.
Note
If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.
You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.
Subtype and Conversion Character
Double-precision hexadecimal, octal, or decimal value
Example: %bx prints pi as 400921fb54442d18
Single-precision hexadecimal, octal, or decimal value
Example: %tx prints pi as 40490fdb
Text Before or After Formatting Operators
Ordinary text to print.
Документация
Запишите данные к текстовому файлу
Синтаксис
Описание
nbytes = fprintf( ___ ) возвращает количество байтов что fprintf записи, с помощью любого из входных параметров в предыдущих синтаксисах.
Примеры
Печать значений буквенного текста и массива
Распечатайте несколько числовых значений и буквенного текста на экран.
%4.2f в formatSpec введите указывает, что первое значение в каждой линии выхода является числом с плавающей запятой с шириной поля четырех цифр, включая две цифры после десятичной точки. %8.3f в formatSpec введите указывает, что второе значение в каждой линии выхода является числом с плавающей запятой с шириной поля восьми цифр, включая три цифры после десятичной точки. \n управляющий символ, который запускает новую строку.
Печать с двойной точностью значения как Целые числа
Явным образом преобразуйте значения с двойной точностью с частями к целочисленным значениям.
Запись табличных данных в текстовый файл
Просмотрите содержимое файла с type команда.
Записание количества байтов к файлу
Запишите данные к файлу и возвратите количество записанных байтов.
fprintf функция записала 96 байтов в файл.
Просмотрите содержимое файла с type команда.
Отображение гиперссылок в командном окне
Отобразите гиперссылку (веб-сайт MathWorks) на экране.
Входные параметры
fileID — Идентификатор файла
1 (значение по умолчанию) | 2 | скаляр
Идентификатор файла, заданный как одно из следующего:
1 для стандартного вывода (экран).
2 для стандартной погрешности.
Типы данных: double
formatSpec — Формат выходных полей
форматирование операторов
Формат выходных полей, заданных операторов форматирования использования. formatSpec также может включать обычный текст и специальные символы.
formatSpec может быть вектор символов в одинарных кавычках, или, запускающийся в R2016b, скаляре строки.
Эта таблица показывает символы преобразования, чтобы отформатировать числовые и символьные данные как текст.
Целое число, подписанное
Целое число, без знака
Базируйтесь 8 (восьмеричный)
Основывайте 16 (шестнадцатеричных), строчных букв a F
Число с плавающей запятой
Представление с фиксированной точкой (Используют оператор точности, чтобы задать количество цифр после десятичной точки.)
Экспоненциальное представление, такое как 3.141593e+00 (Используйте оператор точности, чтобы задать количество цифр после десятичной точки.)
Символы или строки
Дополнительный идентификатор, флаги, ширина поля, точность и операторы подтипа далее задают формат синтезируемого текста.
Примечание: Если входной параметр является массивом, вы не можете использовать идентификаторы, чтобы задать конкретные элементы массива от того входного параметра.
Лево-выровнять по ширине.
Пример: %-5.2f
Пример: %-10s
Вставьте пробел перед значением.
Пример: % 5.2f
Заполните к ширине поля нулями перед значением.
Пример: %05.2f
Измените выбранные числовые преобразования:
Минимальное количество символов, чтобы распечатать. Оператор ширины поля может быть номером или звездочкой ( * ) относиться к входному параметру.
Когда вы задаете * как оператор ширины поля, другие входные параметры должны обеспечить и ширину и значение, которое будет распечатано. Ширины и значения могут быть парами аргументов или парами в числовом массиве. С * как оператор ширины поля, можно распечатать различные значения с различными ширинами.
Функция заполняет к ширине поля пробелами перед значением, если в противном случае не задано флагами.
Количество цифр справа от десятичной точки
Пример: ‘%.4f’ печать pi как ‘3.1416’
Количество значительных цифр
Пример: ‘%.4g’ печать pi как ‘3.142’
Оператор точности может быть номером или звездочкой ( * ) относиться к аргументу.
Когда вы задаете * как полевой оператор точности, другие входные параметры должны обеспечить и точность и значение, которое будет распечатано. Точность и значения могут быть парами аргументов или парами в числовом массиве. С * как оператор точности, можно распечатать различные значения к различной точности.
Когда вы задаете *.* как ширина поля и операторы точности, необходимо задать ширину поля, точность и значения как триплеты.
Примечание
Если вы задаете оператор точности для значений с плавающей точкой, который превышает точность входного типа числовых данных, результаты не могут совпадать с входными значениями к точности, которую вы задали. Результат зависит от вашего компьютерного оборудования и операционной системы.
Можно использовать оператор подтипа, чтобы распечатать значение с плавающей точкой как его восьмеричное, десятичное, или шестнадцатеричное значение. Оператор подтипа сразу предшествует символу преобразования. Эта таблица показывает преобразования, которые могут использовать подтипы.
Тип входного значения
Подтип и символ преобразования
Тип выходного значения
Число с плавающей запятой
С двойной точностью шестнадцатеричное, восьмеричное, или десятичное значение
Пример: %bx печать pi как 400921fb54442d18
Шестнадцатеричное, восьмеричное, или десятичное значение с одинарной точностью
Пример: %tx печать pi как 40490fdb
Текст прежде или после операторов форматирования
Обычный текст, чтобы распечатать.
fprintf
Write data to text file
Syntax
Description
nbytes = fprintf( ___ ) returns the number of bytes that fprintf writes, using any of the input arguments in the preceding syntaxes.
Examples
Print Literal Text and Array Values
Print multiple numeric values and literal text to the screen.
%4.2f in the formatSpec input specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point. %8.3f in the formatSpec input specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point. \n is a control character that starts a new line.
Print Double-Precision Values as Integers
Explicitly convert double-precision values with fractions to integer values.
Write Tabular Data to Text File
MATLAB ® import functions, all UNIX ® applications, and Microsoft Word and WordPad recognize ‘\n’ as a newline indicator.
View the contents of the file with the type command.
Get Number of Bytes Written to File
Write data to a file and return the number of bytes written.
The fprintf function wrote 96 bytes to the file.
View the contents of the file with the type command.
Display Hyperlinks in Command Window
Display a hyperlink (The MathWorks Web Site) on the screen.
Input Arguments
fileID — File identifier
1 (default) | 2 | scalar
File identifier, specified as one of the following:
1 for standard output (the screen).
2 for standard error.
Data Types: double
formatSpec — Format of output fields
formatting operators
Format of the output fields, specified using formatting operators. formatSpec also can include ordinary text and special characters.
formatSpec can be a character vector in single quotes, or, starting in R2016b, a string scalar.
This table shows conversion characters to format numeric and character data as text.
Base 16 (hexadecimal), lowercase letters a – f
Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)
Exponential notation, such as 3.141593e+00 (Use a precision operator to specify the number of digits after the decimal point.)
Characters or strings
The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.
Note: If an input argument is an array, you cannot use identifiers to specify particular array elements from that input argument.
Always print a sign character (+ or –) for any numeric value.
Example: %+5.2f
Right-justify text.
Example: %+10s
Insert a space before the value.
Example: % 5.2f
Pad to field width with zeros before the value.
Example: %05.2f
Modify selected numeric conversions:
Minimum number of characters to print. The field width operator can be a number, or an asterisk ( * ) to refer to an input argument.
When you specify * as the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With * as the field width operator, you can print different values with different widths.
The function pads to field width with spaces before the value unless otherwise specified by flags.
Number of digits to the right of the decimal point
Example: ‘%.4f’ prints pi as ‘3.1416’
Number of significant digits
Example: ‘%.4g’ prints pi as ‘3.142’
The precision operator can be a number, or an asterisk ( * ) to refer to an argument.
When you specify * as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With * as the precision operator, you can print different values to different precisions.
When you specify *.* as field width and precision operators, you must specify field widths, precisions, and values as triplets.
Note
If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.
You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.
Subtype and Conversion Character
Double-precision hexadecimal, octal, or decimal value
Example: %bx prints pi as 400921fb54442d18
Single-precision hexadecimal, octal, or decimal value
Example: %tx prints pi as 40490fdb
Text Before or After Formatting Operators
Ordinary text to print.
Fprintf matlab что это
Write formatted data to file
The format argument is a string containing C language conversion specifications. A conversion specification controls the notation, alignment, significant digits, field width, and other aspects of output format. The format string can contain escape characters to represent nonprinting characters such as newline characters and tabs.
Conversion specifications begin with the % character and contain these optional and required elements:
You specify these elements in the following order:
You can control the alignment of the output using any of these optional flags.
Field Width and Precision Specifications
You can control the width and precision of the output by including these options in the format string.
Conversion characters specify the notation of the output.
This table lists the escape character sequences you use to specify nonprinting characters in a format specification.
| Character | Description | |||||||||||||||
| \b | Backspace | |||||||||||||||
| \f | Form feed | |||||||||||||||
| \n | New line | |||||||||||||||
| \r | Carriage return | |||||||||||||||
| \t | Horizontal tab | |||||||||||||||
| \\ | Backslash | |||||||||||||||
| \» or » When writing text to a file on Windows, it is recommended that you open the file in write-text mode (e.g., fopen(file_id, ‘wt’) ). This ensures that lines in the file are terminated in such a way as to be compatible with all applications that might use the file. The fprintf function behaves like its ANSI C language namesake with these exceptions and extensions:
| ||||||||||||||||







