MATLAB Answers

convert cell array of different data type char and number to matrix

26 views (last 30 days)
shawin on 21 Jan 2016
Commented: Kirby Fears on 22 Jan 2016
I have a xls sheet and i read it using xlsread() function , and its produce a cell array of character and number. the first column ( ID: Char&number) and the rest is number , i used cell2mat() , but it does not work it produce error data should be same type. then i separate the ID from the whole cell it produce another cell ( ID ) then when i tried convert it to mat , iam receiving error again ? please any suggestion.

Answers (2)

Kirby Fears
Kirby Fears on 21 Jan 2016
Edited: Kirby Fears on 21 Jan 2016
You have several options.
1) If every cell in your cell array contains a scalar double value, cell2mat() will work properly. You probably still have other data types mixed into your cell array.
2) You can get a numeric array directly from xlsread by using xlsread with this syntax: num = xlsread('filename.xls');
3) Instead of xlsread, try using readtable('filename.xls'). This will return a table instead of a cell array or double array.

Walter Roberson
Walter Roberson on 21 Jan 2016
[num, txt, raw] = xlsread('YourFile.xls');
then num should already be the numeric data without the first (text) column.
If you have a particular reason for creating a subset:
raw_without_1 = raw(:,2:end);
[nn_r, nn_c] = find(~cellfun(@isnumeric, raw_without_1));
if ~isempty(nn_r)
content = raw_without_1{nn_r(1),nn_c(1)};
fprintf('Some cells are not numbers, such as location (%d,%d) which has class "%s" and value\n', nn_r(1), nn_c(1), class(content));
num = [];
num = cell2mat(raw_without_1);
Kirby Fears
Kirby Fears on 22 Jan 2016
Indeed readtable() seems like the best option here. The result will be a table instead of a cell array or numeric array. You can learn to interact with tables here .

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!