how to change a cell in a string to a string in a table
21 views (last 30 days)
Show older comments
Hey everyone, I'm trying to use the 'unique' matlab function.
unique(table.row)
When I try this I get the error "Cell array input must be a cell array of character vectors.". I think this is because my table is in the form
table.row(1) = {'string'}
But it needs to be in the form
table.row(1) = 'string'.
I tried to fix this by using the for loop below
for n= 1:numel(table.row)
table.row(n)=table.row{n};
end
but doing this I get the output error "Conversion to cell from char is not possible."
3 Comments
Adam Danz
on 19 Mar 2025
% This reproduces your error
T = table(num2cell(string(['a':'z']')),'VariableNames',{'row'})
unique(T.row) % ERROR!
I've updated my answer to include 3 ways to convert the data type of table variables.
Accepted Answer
Adam Danz
on 23 Jul 2019
Edited: Adam Danz
on 19 Mar 2025
Three ways to convert data types within a table or timetable
Example: Convert the first and last columns from a cellstring to string array.
T1 = readtable('outages.csv');
head(T1,3)
T2 = convertvars(T1,["Region","Cause"],"string");
head(T2,3)
2. Set the VariableTypes property of the table or timetable (R2024b)
Example: Convert the last names to strings and the Gender to categorical.
T1 = readtable("patients.xls");
head(T1,3)
T1.Properties.VariableTypes([1,2]) = ["string","categorical"];
head(T1,3)
Tip: To replace all "cell" types to "string", use:
T1.Properties.VariableTypes = strrep(T1.Properties.VariableTypes,'cell','string');
3. Reassign the table variable
Example: Convert the "Cause" variable from cellstring to categorical.
T1 = readtable('outages.csv');
head(T1,3)
T1.Cause = categorical(T1.Cause);
head(T1,3)
Example, convert between character vectors or cellstrings and string arrays using convertStringsToChars or convertCharsToStrings (R2017b)
T1.Region = convertCharsToStrings(T1.Region);
head(T1,3)
2 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!