Convert numbers to strings in a cell array in MATLAB

Maddy picture Maddy · Feb 25, 2013 · Viewed 12.7k times · Source

I have a cell array with numbers and string data. I need to convert the numbers to strings so that I can use the unique() function.

a = {1; 4; 'lf'}
result --> {'1', '4', 'lf'}; % Now unique() function can be used

There are online solutions to handle a case where the column was numerical. But those cannot be used here as at least 1 row has string as data. A vectorized solution shall be appreciated.

Answer

gevang picture gevang · Feb 25, 2013

Use cellfun() for applying num2str() to every cell element:

result = cellfun(@num2str, a, 'UniformOutput', false)

This (with UniformOutput set to false) will automatically handle the non-scalar, char elements of the array.