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.

Answers


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

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

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'

Now after MATLAB 2016b, you can simply use

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

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)


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

Need Your Help

Different ways of adding to Dictionary

c# optimization dictionary

What is the difference in Dictionary.add(key, value) and Dictionary[key] = value?

How to limit the result count of NSFetchRequest?

iphone objective-c ios core-data nspredicate

I want to have a feature of "Recent 20 Items" in my iOS app. I use Core Data and NSFetchRequest. How can I limit the result number to 20 to achieve this? Thank you in advance!