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

조회 수: 371 (최근 30일)
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.

채택된 답변

Santhana Raj
Santhana Raj 2017년 5월 9일
x=2;
y= ['I have' num2str(x) 'dogs'];
  댓글 수: 6
Steven Lord
Steven Lord 2017년 5월 9일
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
Walter Roberson
Walter Roberson 2017년 5월 9일
Right, sprintf() outputs a character vector.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 5월 9일
y = sprintf('I have %d dogs', x);
  댓글 수: 2
Gennaro Arguzzi
Gennaro Arguzzi 2017년 5월 9일
Hi @Walter Roberson, y is a character vector (e.g. y=sprintf(2222) has 1x4 dimensions). My goal is to obtain a string.
Walter Roberson
Walter Roberson 2017년 5월 9일
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) }

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by