How create string like this: word+number+word with number=num2str(x)

Hi everyone,
how could I write a string like the following word+number+word with number=num2str(x). For example:
x=2; x_str=num2str(x); y='I have' x_str 'dogs'
Thank you for your help.

 Accepted Answer

x=2;
y= ['I have' num2str(x) 'dogs'];

6 Comments

Hi @Santhana Raj, the definition of the string array y is not possible in Matlab 2015?
The code here should work in R2015* other than the fact that you probably want to add some blanks,
y= ['I have ' num2str(x) ' dogs'];
In R2016b, MATLAB introduced a new string datatype; as of R2017a that allows for syntax such as
"I have " + 2 +" dogs"
but that was not possible in R2015*
String arrays were introduced in release R2016b. In releases R2015a or R2015b, you will need to make a char array (like Santhana Raj did.)
Hi @Steven Lord, the statement sprintf() creates only character vector?
If you're using a release that includes the string data type and you specify the formatSpec input to sprintf as a string rather than a char vector, you will receive a string rather than a char vector as output.
A = sprintf(string('abc %d def'), 17);
B = sprintf("abc %d def", 17); % release R2017a and later
Right, sprintf() outputs a character vector.

Sign in to comment.

More Answers (1)

y = sprintf('I have %d dogs', x);

2 Comments

Hi @Walter Roberson, y is a character vector (e.g. y=sprintf(2222) has 1x4 dimensions). My goal is to obtain a string.
MATLAB does not have a string data type before R2016b, on character vectors. It is common to put character vectors inside cell arrays, such as
{sprintf('I have %d dogs', x), 'I have no cats', sprintf('I have %d iguanas', y) }

Sign in to comment.

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!