Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a numeric array into a string cell array

Given the matrix:- A = [0 1 2 3 4 5];

I want to convert it into a string cell array like this: A = {'0' '1' '2' '3' '4' '5'};

I am able to do this using:

A = [0 1 2 3 4 5];

for i=1:6
    A1{i}= num2str(A(i));
end
A1

I want to do this in a simpler way and without a loop.

like image 486
Sardar Usama Avatar asked Feb 22 '26 21:02

Sardar Usama


2 Answers

Another one line method with num2str and strsplit:

A1 = strsplit(num2str(A))
like image 80
obchardon Avatar answered Feb 25 '26 12:02

obchardon


you may use arrayfun in combination with an anonymous function:

B = arrayfun(@(x) {num2str(x)}, A);

cellfun is a little bit faster and works also fine:

B = cellfun(@num2str, num2cell(A), 'uni', 0);

fastest solution is an improved version of this solution (credits to obchardon)

B = regexp(num2str(A), '\s+', 'split');
like image 25
serial Avatar answered Feb 25 '26 11:02

serial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!