29

How can I convert [12 25 34 466 55] to an array of strings ['12' '25' '34' '466' '55']? The conversion functions I know convert that array to one string representing the entire array.

5 Answers 5

32

An array of strings has to be a cell array. That said:

s = [12 25 34 466 55]
strtrim(cellstr(num2str(s'))')
Sign up to request clarification or add additional context in comments.

2 Comments

A better way than what I wrote above.
This is over twice as fast than both arrayfun and cellfun. +1
13

Now after MATLAB 2016b, you can simply use

s = [12 25 34 466 55]; 
string(s)

Comments

12

Using arrayfun together with num2str would work:

>> A = [12 25 34 466 55]
A =
   12    25    34   466    55

>> arrayfun(@num2str, A, 'UniformOutput', false)
ans = 
    '12'    '25'    '34'    '466'    '55'

1 Comment

why not arrayfun(@num2str, A, 'UniformOutput', false)? Same concept, same output, but you avoid the "from-cell" and "to-cell" conversions.
0

In MATLAB, ['12' '25' '34' '466' '55'] is the same as a single string containing those numbers. That is to say:

['12' '25' '34' '466' '55']

ans =

12253446655

I need more context here for what you are trying to accomplish, but assuming you want to still be able to access each individual number as a string, a cell array is probably the best approach you can take:

A = [1 2 3]
num2cell(num2str(A))

(Of course, you'd still have to remove the stray spaces from the ans)

1 Comment

Even if you remove the stray spaces, you end up with a cell array of strings that contains each digit separately. Swap the order of num2cell and num2str instead. cellfun(@num2str,num2cell(s),'UniformOutput',false) gets the job done nicely.
0

Starting from R2016b there is also the compose function:

>> A = [12 25 34 466 55]

A =

    12    25    34   466    55

>> compose("%d", A)

ans = 

  1×5 string array

    "12"    "25"    "34"    "466"    "55"'''

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.