How to replace all string type by char type in a cell array?

How to replace all string type by char type in a cell array?

You can use cellstr (confusingly, despite str suggesting string) to convert strings to character arrays without looping or cellfun… the docs state the following:

C = cellstr(A) converts A to a cell array of character vectors. The input array A can be a character array, a categorical array, or, starting in R2016b, a string array.

test = {hello, world, 0.3; how, are, you}; % multi-type test cell array
ind = cellfun(@isstring, test);                      % indexing for string type items
test(ind) = cellstr(test(ind))                       % char-ify the strings!

A cellfun performance note for class checks:

In both mine and Luis answers, cellfun is used to determine which elements are strings. You can improve the performance of cellfun for this task…

Per the cellfun docs, there are some character array options which are much quicker than their function-handle counterparts. For the isstring indexing, its likely a lot faster to run the first of these:

% rapid
ind = cellfun(isclass, test, string);
% akin to looping
ind = cellfun(@isstring, test);

They have the same output, in a simple test I see a 4x speed improvement:

% Create large test array of random strings
c = cell(100,1000);
c = cellfun(@(x) string(char(randi([65,122],1,10))), c, uni, 0);

% Create functions for benchmarking 
f=@()cellfun(isclass, c, string);

% Timing on MATLAB R2017b
timeit( f ) % >> 0.017sec
timeit( g ) % >> 0.066sec 

You can use cellfun, but it has more or less the same performance as a loop:

test = {hello, world, 0.3; how, are, you};
ind = cellfun(@isstring, test);
test(ind) = cellfun(@char, test(ind), UniformOutput, false)

How to replace all string type by char type in a cell array?

As of MATLAB R2017b you can use convertstringstochars:

[test{:}] = convertStringsToChars(test{:});

Leave a Reply

Your email address will not be published. Required fields are marked *