5

I would like to concatenate strings. I tried using strcat:

x = 5;
m = strcat('is', num2str(x)) 

but this function removes trailing white-space characters from each string. Is there another MATLAB function to perform string concatenation which maintains trailing white-space?

5 Answers 5

12

You can use horzcat instead of strcat:

>> strcat('one ','two')
ans =
onetwo
>> horzcat('one ','two')
ans =
one two

Alternatively, if you're going to be substituting numbers into strings, it might be better to use sprintf:

>> x = 5;
>> sprintf('is %d',x)
ans =
is 5
Sign up to request clarification or add additional context in comments.

Comments

4

How about

strcat({' is '},{num2str(5)})

that gives

' is 5'

Comments

2

Have a look at the final example on the strcat documentation: try using horizontal array concatination instead of strcat:

m = ['is ', num2str(x)]

Also, have a look at sprintf for more information on string formatting (leading/trailing spaces etc.).

Comments

2

How about using strjoin ?

x = 5;
m ={'is', num2str(x)};
strjoin(m, ' ')

Comments

-2

What spaces does this not take into account ? Only the spaces you haven't mentioned ! Did you mean:

m = strcat( ' is ',num2str(x) ) 

perhaps ?

Matlab isn't going to guess (a) that you want spaces or (b) where to put the spaces it guesses you want.

1 Comment

that space you put there, will be trimmed off if you use strcat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.