3

I have a vector a = [1 2 3 4 5] how would I make it so b = '12345'?

I have tried b = num2str(a) but it outputs 1 2 3 4 5.

2 Answers 2

4

You can specify the format in num2str, much as you would in C's function sprintf:

b = num2str(a,'%i');

Or use sprintf:

b = sprintf('%i',a);

If a contains only single-digit numbers, you can also convert to char directly:

b = char(a+'0');
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much Luis for helping me with this, that was exactly what I was looking for. Another question I have is how would I make the first element of c have this value? Such as c(1) = 12345?
I understood from your question that the desired result '12345' was a string, not a number (otherwise use Shai's answer less the num2str part). So you want to assign a string to the first element of a variable c? If c has to store other strings of possibly different lengths, c should be a cell array; and you'd just do c{1} = b
Thank you Luis Mendo and Shai for your inputs. Sorry I should of been more clear with my first question as I ultimately wanted the output from the array a to be a string '12345' so I could put it into a position of another array.
1

You need to convert yor vector to a single number first (assuming all elements are in range 0..9):

a = 1:5;
num = ( 10.^((numel(a)-1):-1:0) ) * a'; %'
b = num2str( num )

You can try this code here.

Comments

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.