Many MATLAB programmers are often surprised to find out that there is no direct way to convert a char
array to a cell
array. In this document, we’ll explain why this conversion is not possible, the workarounds, and some useful features to keep in mind while developing MATLAB solutions.
Background Explanation
A char
array stores values as a sequence of characters. It is used to store text and strings as well as ASCII codes for non-text characters. Output of function calls and constants can also be stored in a char
array.
A cell
array, conversely, acts like a container that holds a variety of data types including strings, numeric values, and MATLAB objects.
What Conversion Is Not Possible?
Simply put, there is no direct or efficient way to convert a char
array directly to a cell
array. If a variable is a char
array, any attempt to cast or store it as a cell
array will result in an error.
The same cannot be said in reverse, as casting a cell
array to a char
array is possible. MATLAB provides a built-in function strjoin()
which can be used to convert a cell
array of strings to a single char
array.
Workarounds
Though it is not possible to make a direct conversion, there are a few workaround strategies that can be used to achieve the same result:
Create an empty cell
array, then iterate through items of the char
array and assign each item to a cell:
charNames = ['John', 'Mary', 'Jack'];
cellNames = cell(1, numel(charNames));
for i=1:numel(charNames)
cellNames{i} = charNames(i);
end
Use strsplit()
to make an array of string
objects, then convert the resultant array to a cell
array:
charNames = 'John,Mary,Jack';
stringNames = strsplit(charNames,',');
cellNames = cell(1,numel(stringNames));
for i=1:numel(stringNames)
cellNames{i} = stringNames(i);
end
Tips and Tricks
The above strategies can help get the job done; however, there are a few additional tips and tricks to optimize your MATLAB code:
If the character array is composed of strings separated by a delimiter, use strsplit()
to create a string
array, then use convertStringsToChars()
to convert the array to a cell
array.
To join a cell
array of strings, use strjoin()
instead of iterating through each item of the array.
FAQs
Q: What is the difference between a char
array and a cell
array?
A: A char
array stores values as a sequence of characters, whereas a cell
array acts like a container that holds a variety of data types including strings, numeric values, and MATLAB objects.
Q: Can I convert a char
array to a cell array?
A: No, conversion from char
to cell
is not possible. You can use workarounds such as creating an empty cell
array, then iterating through items of the char
array and assign each item to a cell; or use strsplit()
to make an array of string
objects, then convert the resultant array to a cell
array.