Method Reference: string.compose

string: str = compose (formatSpec, A)
string: str = compose (formatSpec, A1, …, AN)
string: str = compose (txt)

Format data into a string array or translate escape-character sequences.

str = compose (formatSpec, A) formats the data in the array A according to the formatting operators in formatSpec, which must be a string scalar or character vector, and returns the result in the string array str. The formatting operators are the same as those accepted by the sprintf function. Unlike sprintf, which returns a single character vector, compose returns a string array whose elements correspond to the rows of A.

compose applies formatSpec to each row of A so that str has the same number of rows as A. The size of str is further determined as follows:

  • If the number of columns in A exceeds the number of formatting operators in formatSpec, then formatSpec is applied repeatedly along each row of A, adding columns to str.
  • If the number of columns in A is less than the number of formatting operators, then the operators left without a corresponding value appear unchanged in str.
  • If A has zero columns, then str has the same size as A and no formatting operators are applied.

str = compose (formatSpec, A1, …, AN) formats the data from the arrays A1, …, AN. The formatting operators are assigned to the input arrays in order: once an operator has consumed a value from an input array, it becomes unavailable to the following arrays. All input arrays must be of compatible sizes.

str = compose (txt) translates escape-character sequences, such as '\n' and '\t', in txt and returns the result in str, which has the same size as txt. Any formatting operators in txt are left unchanged.

In all syntaxes, escape-character sequences appearing in literal text are translated and each '%%' literal is converted to a single '%' character, following the same rules as the sprintf function. The only difference from sprintf is that a formatting operator left without a corresponding value is emitted unchanged rather than dropped.

Source Code: string

Example: 1

compose applies a printf-style format to data, returning a string array — one element per row of the data. (The format itself is given as a string.)

 compose (string ('%s scored %d'), string ({'Ann'; 'Bob'}), [7; 9])
ans =
  2x1 string array

    "Ann scored 7"    
    "Bob scored 9"