num2str
Convert numbers to character array
Syntax
Description
s = num2str( A ) converts a numeric array into a character array that represents the numbers. The output format depends on the magnitudes of the original values. num2str is useful for labeling and titling plots with numeric values.
Examples
Default Conversions of Floating-Point Values
Convert the floating-point values returned by pi and eps to character vectors.
Specify Precision
Specify the maximum number of significant digits for floating-point values.
Specify Formatting
Display pi as a floating-point number to a specified precision.
Input Arguments
A — Input array
numeric array
Input array, specified as a numeric array.
Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical
Complex Number Support: Yes
precision — Maximum number of significant digits
positive integer
Maximum number of significant digits in the output string, specified as a positive integer.
Note
If you specify precision to exceed the precision of the input floating-point 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.
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
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: Unlike the sprintf function, num2str does not support identifiers.
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.
Example: ‘%5d’ prints intmax as 2147483647 because the value returned by intmax exceeds the minimum number of characters to print.
If the number of characters to print is less than the field width, then the compose function pads to the field width with spaces before the value unless otherwise specified by flags.
However, the num2str function does not pad to the field width with spaces.
Number of digits to print.
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’
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.
Single quotation mark
Character whose Unicode ® numeric value can be represented by the hexadecimal number, N
Example: sprintf(‘\x5A’) returns ‘Z’
Character whose Unicode numeric value can be represented by the octal number, N
Example: sprintf(‘\132’) returns ‘Z’
Notable Behavior of Conversions with Formatting Operators
Numeric conversions print only the real component of complex numbers.
If you apply a text conversion (either %c or %s ) to integer values, MATLAB converts values that correspond to valid character codes to characters.
Output Arguments
s — Text representation of input array
character array
Text representation of the input array, returned as a character array.
num2str does not accept positional identifiers in the formatSpec input argument. For example, num2str([14 15],’%2$X %1$o) returns an error.
If you specify an invalid formatting operator or special character, then num2str prints all text up to the invalid operator or character and discards the rest.
Algorithms
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
The input arguments must be constants.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Документация
Преобразуйте числа в символьный массив
Синтаксис
Описание
s = num2str( A ) преобразует числовой массив в символьный массив, который представляет числа. Выходной формат зависит от величин исходных значений. num2str полезно для графиков маркировки и создания заголовков с числовыми значениями.
Примеры
Преобразования по умолчанию значений с плавающей точкой
Определение точности
Задайте максимальное количество значащих цифр для значений с плавающей точкой.
Определение форматирования
Отобразите pi как число с плавающей запятой к заданной точности.
Входные параметры
A — Входной массив
числовой массив
Входной массив в виде числового массива.
Типы данных: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical
Поддержка комплексного числа: Да
precision — Максимальное количество значительных цифр
положительное целое число
Максимальное количество значительных цифр в выводимой строке в виде положительного целого числа.
Примечание
Если вы задаете precision чтобы превысить точность входа тип данных с плавающей точкой, результаты не могут совпадать с входными значениями к точности, которую вы задали. Результат зависит от вашего компьютерного оборудования и операционной системы.
Типы данных: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
formatSpec — Формат выходных полей
форматирование операторов
Формат выходных полей, заданных операторов форматирования использования. formatSpec также может включать обычный текст и специальные символы.
formatSpec может быть вектор символов в одинарных кавычках, или, запускающийся в R2016b, строковом скаляре.
Эта таблица показывает символы преобразования, чтобы отформатировать числовые и символьные данные как текст.
Целое число, со знаком
Целое число, без знака
Базируйтесь 8 (восьмеричный)
Основывайте 16 (шестнадцатеричных), строчных букв a F
Число с плавающей запятой
Представление с фиксированной точкой (Используют оператор точности, чтобы задать количество цифр после десятичной точки.)
Экспоненциальное представление, такое как 3.141593e+00 (Используйте оператор точности, чтобы задать количество цифр после десятичной точки.)
Символы или строки
Дополнительный идентификатор, флаги, ширина поля, точность и операторы подтипа далее задают формат синтезируемого текста.
Примечание: в отличие от этого, sprintf функция, num2str не поддерживает идентификаторы.
Лево-выровнять по ширине.
Пример: %-5.2f
Пример: %-10s
Вставьте пробел перед значением.
Пример: % 5.2f
Заполните к ширине поля нулями перед значением.
Пример: %05.2f
Измените выбранные числовые преобразования:
Минимальное количество символов, чтобы распечатать.
Если количество символов, чтобы распечатать меньше ширины поля, то compose функционируйте клавиатуры к ширине поля с пробелами перед значением, если в противном случае не задано флагами.
Однако num2str функция не заполняет к ширине поля пробелами.
Количество цифр, чтобы распечатать.
Количество цифр справа от десятичной точки
Пример: ‘%.4f’ печать pi как ‘3.1416’
Количество значительных цифр
Пример: ‘%.4g’ печать pi как ‘3.142’
Примечание
Если вы задаете оператор точности для значений с плавающей точкой, который превышает точность входного типа числовых данных, результаты не могут совпадать с входными значениями к точности, которую вы задали. Результат зависит от вашего компьютерного оборудования и операционной системы.
Можно использовать оператор подтипа, чтобы распечатать значение с плавающей точкой как его восьмеричное, десятичное, или шестнадцатеричное значение. Оператор подтипа сразу предшествует символу преобразования. Эта таблица показывает преобразования, которые могут использовать подтипы.
Тип входного значения
Подтип и символ преобразования
Тип выходного значения
Число с плавающей запятой
С двойной точностью шестнадцатеричное, восьмеричное, или десятичное значение
Пример: %bx печать pi как 400921fb54442d18
Шестнадцатеричное, восьмеричное, или десятичное значение с одинарной точностью
Пример: %tx печать pi как 40490fdb
Текст прежде или после операторов форматирования
Обычный текст, чтобы распечатать.
Обратная косая черта
Символ, чей Unicode ® числовое значение может быть представлено шестнадцатеричным номером, N
Пример: sprintf(‘\x5A’) возвращает ‘Z’
Символ, числовое значение Unicode которого может быть представлено восьмеричным числом, N
Пример: sprintf(‘\132’) возвращает ‘Z’
Известное поведение преобразований с операторами форматирования
Числовые преобразования распечатывают только действительный компонент комплексных чисел.
Если вы применяете текстовое преобразование (любой %c или %s ) к целочисленным значениям MATLAB преобразует значения, которые соответствуют кодам допустимого символа к символам.
Выходные аргументы
s — Текстовое представление входного массива
массив символов
Текстовое представление входного массива, возвращенного как символьный массив.
Советы
num2str не принимает позиционные идентификаторы в formatSpec входной параметр. Например, num2str([14 15],’%2$X %1$o) возвращает ошибку.
Если вы задаете недопустимый оператор форматирования или специальный символ, то num2str печать весь текст до недействительного оператора или символа и отбрасываний остальные.
Пример: если formatSpec ‘value = %z’ то num2str печать ‘value =’ потому что %z не оператор форматирования.
Пример: если formatSpec ‘character \x99999 = %s’ то num2str печать ‘character’ потому что \x99999 не допустимый специальный символ.
Алгоритмы
Расширенные возможности
Генерация кода C/C++
Генерация кода C и C++ с помощью MATLAB® Coder™.
Указания и ограничения по применению:
Входные параметры должны быть константами.
Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.
Массивы графического процессора
Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.
Смотрите также
Открытый пример
У вас есть модифицированная версия этого примера. Вы хотите открыть этот пример со своими редактированиями?
Документация MATLAB
Поддержка
© 1994-2021 The MathWorks, Inc.
1. Если смысл перевода понятен, то лучше оставьте как есть и не придирайтесь к словам, синонимам и тому подобному. О вкусах не спорим.
2. Не дополняйте перевод комментариями “от себя”. В исправлении не должно появляться дополнительных смыслов и комментариев, отсутствующих в оригинале. Такие правки не получится интегрировать в алгоритме автоматического перевода.
4. Не имеет смысла однотипное исправление перевода какого-то термина во всех предложениях. Исправляйте только в одном месте. Когда Вашу правку одобрят, это исправление будет алгоритмически распространено и на другие части документации.
5. По иным вопросам, например если надо исправить заблокированное для перевода слово, обратитесь к редакторам через форму технической поддержки.
num2str
Convert numbers to character array
Syntax
Description
s = num2str( A ) converts a numeric array into a character array that represents the numbers. The output format depends on the magnitudes of the original values. num2str is useful for labeling and titling plots with numeric values.
Examples
Default Conversions of Floating-Point Values
Convert the floating-point values returned by pi and eps to character vectors.
Specify Precision
Specify the maximum number of significant digits for floating-point values.
Specify Formatting
Display pi as a floating-point number to a specified precision.
Input Arguments
A — Input array
numeric array
Input array, specified as a numeric array.
Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical
Complex Number Support: Yes
precision — Maximum number of significant digits
positive integer
Maximum number of significant digits in the output string, specified as a positive integer.
Note
If you specify precision to exceed the precision of the input floating-point 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.
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
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: Unlike the sprintf function, num2str does not support identifiers.
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.
Example: ‘%5d’ prints intmax as 2147483647 because the value returned by intmax exceeds the minimum number of characters to print.
If the number of characters to print is less than the field width, then the compose function pads to the field width with spaces before the value unless otherwise specified by flags.
However, the num2str function does not pad to the field width with spaces.
Number of digits to print.
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’
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.
Single quotation mark
Character whose Unicode ® numeric value can be represented by the hexadecimal number, N
Example: sprintf(‘\x5A’) returns ‘Z’
Character whose Unicode numeric value can be represented by the octal number, N
Example: sprintf(‘\132’) returns ‘Z’
Notable Behavior of Conversions with Formatting Operators
Numeric conversions print only the real component of complex numbers.
If you apply a text conversion (either %c or %s ) to integer values, MATLAB converts values that correspond to valid character codes to characters.
Output Arguments
s — Text representation of input array
character array
Text representation of the input array, returned as a character array.
num2str does not accept positional identifiers in the formatSpec input argument. For example, num2str([14 15],’%2$X %1$o) returns an error.
If you specify an invalid formatting operator or special character, then num2str prints all text up to the invalid operator or character and discards the rest.
Algorithms
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
The input arguments must be constants.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Str2num matlab что это
Работа с символьными данными
Основные функции символьных данных
Операции над строками
Преобразование символов и строк
Функции преобразования систем счисления
Вычисление строковых выражений
Функции обработки массивов символов или рядов этих массивов (строкой в терминологии MATLAB называется любой массив символов или ряд массива символов) для математической системы могут показаться второстепенными. Однако это не так. Строковое представление данных лежит в основе символьной математики, арифметики произвольной точности и многочисленных программных конструкций, не говоря уже о том, что оно широко применяется в базах данных и массивах ячеек. Этот урок посвящен возможностям обработки символьных переменных и выражений в системе MATLAB.
Основные функции символьных данных
В основе представления символов в строках лежит их кодирование с помощью сменных таблиц кодов. Такие таблицы ставят в однозначное соответствие каждому символу некоторый код со значением от 0 до 255.
Вектор, содержащий строку символов, в системе MATLAB задается следующим образом:
S= ‘Any Characters’ — вектор, компонентами которого являются числовые коды, соответствующие символам [Символ внутри такой строки дублируется (заменяется на »). — Примеч. ред.].
Первые 127 чисел — это коды ASCII, представляющие буквы латинского языка, цифры и спецзнаки. Они образуют основную таблицу кодов. Вторая таблица (коды от 128 до 255) является дополнительной и может использоваться для представления символов других языков, например русского. Длина вектора S соответствует числу символов в строке, включая пробелы. Апостроф внутри строки символов должен вводиться как два апострофа ‘ ‘.
К основным строковым функциям относятся следующие:
char (X) — преобразует массив X положительных целых чисел (числовых кодов от 0 до 65 535) в массив символов системы MATLAB (причем только первые 127 кодов — английский набор ASCII, со 128 до 255 — расширенный набор ASCII) и возвращает его, на платформе Windows при значении выше 65 535 выдает предупреждение об ошибке, но возвращает русскую букву я (я повторяется так же, как char(255+256rt), где п — целые неотрицательные числа) [Результат char(x) при х>65535 зависит от платформы, русификации и т. д. — Примеч. ред.];
Convert Numeric Values to Text
This example shows how to convert numeric values to text and append them to larger pieces of text. For example, you might want to add a label or title to a plot, where the label includes a number that describes a characteristic of the plot.
Convert to Strings
Before R2016b, convert to character vectors using num2str .
To convert a number to a string that represents it, use the string function.
The string function converts a numeric array to a string array having the same size.
You can specify the format of the output text using the compose function, which accepts format specifiers for precision, field width, and exponential notation.
If the input is a numeric array, then compose returns a string array. Return a string array that represents numbers using exponential notation.
Add Numbers to Strings
Before R2016b, convert numbers to character vectors and concatenate characters in brackets, [] .
The simplest way to combine text and numbers is to use the plus operator ( + ). This operator automatically converts numeric values to strings when the other operands are strings.
For example, plot a sine wave. Calculate the frequency of the wave and add a string representing that value in the title of the plot.
Sometimes existing text is stored in character vectors or cell arrays of character vectors. However, the plus operator also automatically converts those types of data to strings when another operand is a string. To combine numeric values with those types of data, first convert the numeric values to strings, and then use plus to combine the text.
Character Codes
If your data contains integers that represent Unicode® values, use the char function to convert the values to the corresponding characters. The output is a character vector or array.
Before R2016b, use num2str to convert the numeric value to a character vector, and then concatenate.
Hexadecimal and Binary Values
For example, set a bit in a binary value. If you specify the binary value using a literal, then it is stored as an integer. After setting one of the bits, display the new binary value as text using the dec2bin function.



