Search code examples
arraysstringmatlabcell

Convert cell array to array of strings


I have imported some information from Excel, that's both strings and numbers. I read the Excel-file in MATLAB in raw format

Now, I have a column in a big matrix as

 [1]
 '1A'
 [2]
 [3]
 [4]
 [505]
 [601]
 [7]
 [8]

this is how the xlsread command gave it to me. I want to convert all these into strings like ['1' , '1A', '2' and so on..] .

I am struggling to do it. I want no blank spaces in each element. I mean it should not be like [ ' 1', ' 1A', ' 2' and so on]....


Solution

  • Try to combine cellfun and num2str like this:

    A = {1, '1A', 2, 3, 4, 505, 601, 7, 8}'
    str = cellfun(@(c) num2str(c), A, 'UniformOutput', false).'
    str = 
    
        '1'    '1A'    '2'    '3'    '4'    '505'    '601'    '7'    '8'
    

    You can use num2str on stings, so you do not have to check if variable is a string or a numeric value. Note that the spaces in the result are between the elements, and not in the elements itself. So,

    str(1)  
    ans =    
        '1'    
    str(2)    
    ans =     
        '1A'
    

    If your input data may contain spaces (your sample didn't), you can eliminate those by using an additional cellfun like this:

    cellfun(@(c) c(c~=' '), str, 'UniformOutput', false) 
    

    Side note: In most MATLAB functions, you can shorten parameter names, such as UniformOutput, false. This can be un, 0, uni, 0 ... etc, as long as the letters represent a unique parameter and can't mean something else. This is a nice trick if you write it in the command window, but I would avoid it in real code, as it could possibly break the code if The MathWorks determines to create a parameter called unit, UniformInput or something else starting with uni. Just a little tip =)