2

I'm stuck with a supposedly simple problem in MATLAB. I have a 1x43 cell array that looks like this (note the space before each value):

labels = {' 1', ' 2', ' 3', ... , ' 43'};

And I simply want to convert it to a numeric vector of dimensions 1x43 that will look like this:

labels_numeric = [1 2 3 ... 43];

Anyone could hint me the right trick for this?

2 Answers 2

4

You can collect the individual character arrays into a single character array, then use str2num to convert it:

labels_numeric = str2num([labels{:}]);

Or even easier, just use str2double:

labels_numeric = str2double(labels);
Sign up to request clarification or add additional context in comments.

Comments

1

gnovice's answer is the simplest solution to this specific problem, but in general if you want to turn a cell array into a numeric one by applying some transformation to each element you can do so using cellfun. For example if you ask MATLAB for length({'apple' 'orange' 'banana'}) you'll get 3, but if you want the length of each string in the array you can do:

>> cellfun(@length, {'apple' 'orange' 'banana'})

ans =

     5     6     6

You can use an anonymous function, or a handle to a function that you have defined, as the argument to cellfun, so the transformation can be as complex as you need.

As long as the result from your function is a scalar numeric or logical value, the output from cellfun will be a numeric or logical array; otherwise it will be another cell array (and if it varies in size you will need to use the 'UniformOutput', false argument pair)

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.