0

I have a large cell array in Matlab (imported from Excel) containing numbers and strings. Let's say the string part looks like this, just bigger with many columns and lines:

Table{1,1} = 'string A'
Table{2,1} = 'string B'
Table{3,1} = 'string B'

And the number part looks like this just bigger:

Table{1,2} = 5;
Table{2,2} = 10;
Table{3,2} = 15;

I am aware that there are disadvantages of working with arrays (right?), so I consider converting EVERYTHING to a numeric matrix by replacing the strings with numbers. (Possibly as a data set with headings - if you don't advise against that?)

My problem is that I have A LOT of different string entries, and I want to automatically assign a number to each entry, e.g. 1 for 'string A', 2 for 'string B' etc., such that:

Matrix(1,1) = 1
Matrix(2,1) = 2
Matrix(3,1) = 2

etc.

and for the numbers simply:

Matrix(1,2) = Table{1,2};
Matrix(2,2) = Table{2,2};
Matrix(3,2) = Table{3,2};

For the strings, I cannot assign the numbers by individual code for each string, because there are so many different string entries. Is there a way to "automate" it?

I am aware of this help site, https://ch.mathworks.com/help/matlab/matlab_prog/converting-from-string-to-numeric.html, but haven't found anything else helpful. How would you do it?

2
  • In your post you're converting a cell array of characters to a cell array of double entries. It is still a cell array Commented Feb 4, 2018 at 12:56
  • The curly brackets were a typo, I meant to write a matrix of course, sorry! I corrected it above. Commented Feb 5, 2018 at 11:06

1 Answer 1

3

Find the indices of both numbers and character entries in your cell array using isnumeric (or ischar) with cellfun. Then use third output argument of unique (or findgroups which requires R2015b) for assigning numbers to character entries of your cell array. Now just put the numbers into your required matrix as shown below:

tmp = cellfun(@isnumeric,Table);     %Indices of Numbers
Matrix = zeros(size(Table));         %Initialising the matrix
[~, ~, ic] = unique(Table(~tmp));    %Assigning numbers to characters 
Matrix(~tmp) = ic;                   %Putting numbers for characters
%Above two lines can be replaced with Matrix(~tmp) = findgroups(Table(~tmp)); in R2015b
Matrix(tmp) = [Table{tmp}];          %Putting numbers as they are
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.