olamundo
olamundo

Reputation: 24981

Matlab: convert array of number to array of strings

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.

Upvotes: 29

Views: 38653

Answers (5)

MiB_Coder
MiB_Coder

Reputation: 915

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"'''

Upvotes: 0

Roun
Roun

Reputation: 1482

Now after MATLAB 2016b, you can simply use

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

Upvotes: 13

anon
anon

Reputation:

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'

Upvotes: 12

Vish
Vish

Reputation: 2164

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)

Upvotes: 0

Peter
Peter

Reputation: 14927

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

s = [12 25 34 466 55]
strtrim(cellstr(num2str(s'))')

Upvotes: 32

Related Questions