Format data into string or character vector (2024)

Format data into string or character vector

collapse all in page

Syntax

str = sprintf(formatSpec,A1,...,An)

[str,errmsg]= sprintf(formatSpec,A1,...,An)

str = sprintf(literalText)

Description

example

str = sprintf(formatSpec,A1,...,An) formats the data in arrays A1,...,An using the formatting operators specified by formatSpec and returns the resulting text in str. The sprintf function formats the values in A1,...,An in column order. If formatSpec is a string, then so is the output str. Otherwise, str is a character vector.

To return multiple pieces of formatted text as a string array or a cell array of character vectors, use the compose function.

[str,errmsg]= sprintf(formatSpec,A1,...,An) returnsan error message as a character vector when the operation is unsuccessful.Otherwise, errmsg is empty.

str = sprintf(literalText) translates escape-character sequences in literalText, such as \n and \t. It returns all other characters unaltered. If literalText contain a formatting operator (such as %f), then str discards it and all characters after.

Examples

collapse all

Floating-Point Formats

Open Live Script

Format a floating-point number using %e, %f, and %g specifiers.

A = 1/eps;str_e = sprintf('%0.5e',A)
str_e = '4.50360e+15'
str_f = sprintf('%0.5f',A)
str_f = '4503599627370496.00000'
str_g = sprintf('%0.5g',A)
str_g = '4.5036e+15'

Literal Text and Array Inputs

Open Live Script

Combine literal text with array values to create a character vector.

str = 'The array is 2x3.'

Specify Formatted Text as String Array

Open Live Script

To return formatted text as a string, specify formatSpec as a string instead of a character vector when you call the sprintf function.

Convert data and return the result as a string.

formatSpec = "The current time is: %d:%d %s";A1 = 11;A2 = 20;A3 = 'a.m.';str = sprintf(formatSpec,A1,A2,A3)
str = "The current time is: 11:20 a.m."

Convert input string. Input arrays that contain text either can be character vectors or strings.

A1 = 2;A2 = 35;A3 = "p.m.";str = sprintf(formatSpec,A1,A2,A3)
str = "The current time is: 2:35 p.m."

Integer Format with Floating-Point Inputs

Open Live Script

Explicitly convert double-precision values to integers.

str = sprintf('%d',round(pi))
str = '3'

Specify Field Width of a Printed Value

Open Live Script

Specify the minimum width of the printed value.

str = sprintf('%025d',123456)
str = '0000000000000000000123456'

The 0 flag in the %025d format specifier requests leading zeros in the output.

Reorder Inputs Using Position Identifier (n$)

Reorder the input values using the n$ position identifier.

A1 = 'X';A2 = 'Y';A3 = 'Z';formatSpec = ' %3$s %2$s %1$s';str = sprintf(formatSpec,A1,A2,A3)
str = ' Z Y X'

Create Character Vector from Values in Cell Array

Open Live Script

C = { 1, 2, 3 ; 'AA','BB','CC'};str = sprintf(' %d %s',C{:})
str = ' 1 AA 2 BB 3 CC'

The syntax C{:} creates a comma-separated list of arrays that contain the contents of each cell from C in column order. For example, C{1}==1 and C{2}=='AA'.

Input Arguments

collapse all

A1,...,AnNumeric, character, or string arrays
arrays

Numeric, character, or string arrays.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string

literalTextInput text without formatting operators
character vector | string scalar

Input text without formatting operators, specified as a character vector or string scalar. sprintf translates any escape-character sequences in literalText.

Data Types: char | string

Output Arguments

collapse all

str — Formatted text
character vector | string scalar

Formatted text, returned as a character vector or a string scalar.The type of output matches the type of formatSpec.

errmsg — Error message
character vector

Error message, returned as a character vector, when the operationis unsuccessful. Otherwise, errmsg is empty.

Tips

  • The sprintf function is similar to fprintf, but fprintf prints to a file or to the Command Window.

  • Format specifiers for the reading functions sscanf and fscanf differfrom the formats for the writing functions sprintf and fprintf.The reading functions do not support a precision field. The widthfield specifies a minimum for writing, but a maximum for reading.

  • If you specify an invalid formatting operator or special character, then sprintf prints all text up to the invalid operator or character and discards the rest.

    Example: If formatSpec is 'value = %z', then sprintf prints 'value =' because %z is not a formatting operator.

    Example: If formatSpec is 'character \x99999 = %s', then sprintf prints 'character' because \x99999 is not a valid special character.

References

[1] Kernighan, B. W., and D. M. Ritchie, TheC Programming Language, Second Edition, Prentice-Hall,Inc., 1988.

[2] ANSI specification X3.159-1989: “ProgrammingLanguage C,” ANSI, 1430 Broadway, New York, NY 10018.

Extended Capabilities

Version History

Introduced before R2006a

See Also

char | fprintf | int2str | num2str | sscanf | fscanf | compose | string

Topics

  • Formatting Text

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Format data into string or character vector (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

Format data into string or character vector (2024)

References

Top Articles
Is It Your Guy's Birthday? 33 Unique Birthday Ideas for Your Boyfriend
Women's Plus Size Formal Dresses
Spasa Parish
The Machine 2023 Showtimes Near Habersham Hills Cinemas
Gilbert Public Schools Infinite Campus
Rentals for rent in Maastricht
159R Bus Schedule Pdf
11 Best Sites Like The Chive For Funny Pictures and Memes
Officially Announcing: Skyward
Momokun Leaked Controversy - Champion Magazine - Online Magazine
Maine Coon Craigslist
How Nora Fatehi Became A Dancing Sensation In Bollywood 
‘An affront to the memories of British sailors’: the lies that sank Hollywood’s sub thriller U-571
Haverhill, MA Obituaries | Driscoll Funeral Home and Cremation Service
Rogers Breece Obituaries
Ella And David Steve Strange
Ems Isd Skyward Family Access
Elektrische Arbeit W (Kilowattstunden kWh Strompreis Berechnen Berechnung)
Omni Id Portal Waconia
Banned in NYC: Airbnb One Year Later
Four-Legged Friday: Meet Tuscaloosa's Adoptable All-Stars Cub & Pickle
Patriot Ledger Obits Today
Harvestella Sprinkler Lvl 2
Storm Prediction Center Convective Outlook
Experience the Convenience of Po Box 790010 St Louis Mo
modelo julia - PLAYBOARD
Poker News Views Gossip
Abby's Caribbean Cafe
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Pull And Pay Middletown Ohio
Navy Qrs Supervisor Answers
Trade Chart Dave Richard
Sweeterthanolives
How to get tink dissipator coil? - Dish De
Lincoln Financial Field Section 110
1084 Sadie Ridge Road, Clermont, FL 34715 - MLS# O6240905 - Coldwell Banker
Kino am Raschplatz - Vorschau
Classic Buttermilk Pancakes
Pick N Pull Near Me [Locator Map + Guide + FAQ]
'I want to be the oldest Miss Universe winner - at 31'
Gun Mayhem Watchdocumentaries
Ice Hockey Dboard
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
A look back at the history of the Capital One Tower
Alvin Isd Ixl
Maria Butina Bikini
Busted Newspaper Zapata Tx
Rubrankings Austin
2045 Union Ave SE, Grand Rapids, MI 49507 | Estately 🧡 | MLS# 24048395
Upgrading Fedora Linux to a New Release
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 6547

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.