lisandrojim
lisandrojim

Reputation: 509

Convert string to num with cellfun

I have the next problem:

A=[2014;20;2012;32155];

Then I want to convert A in a cell array with string characters, with the character A prepended to each of the strings. In other words, I wish to do this if I were to create a manual cell array:

A={'A2014';'A20';'A2012';'A32155'};

Can anybody make this without using a loop? Thanks!

Upvotes: 0

Views: 673

Answers (3)

hoogamaphone
hoogamaphone

Reputation: 1102

Another way would be

formatSpec = 'A%d';
B = strtrim(cellstr(num2str(A(:), formatSpec)));
B = reshape(B, size(A));

Note that you can modify the format of the resulting strings by changing the 'A%d' format specifier to something else. Read the documentation of num2str for more details.

Upvotes: 3

rayryeng
rayryeng

Reputation: 104555

With your edit, you can do this to first convert your numeric array into a cell array of strings like you said:

A = num2cell(A);
A = cellfun(@num2str, A, 'UniformOutput', false);

Once you do this, if my understanding is correct, you want to insert an A character before each string. As such, you can do this:

A = cellfun(@(x) ['A' x], A, 'UniformOutput', false);

You would thus get:

A = 

 'A2014'
 'A20'
 'A2012'
 'A32144'

Upvotes: 2

Vuwox
Vuwox

Reputation: 2359

Like @rayryeng said this works :

A = num2cell(A);
A = cellfun(@num2str, A, 'UniformOutput', false)

Upvotes: 2

Related Questions