user3123955
user3123955

Reputation: 2901

Convert part of cell array containing all strings to doubles

I have a cell array with 9 columns where each cell contains strings, but only the 9th column is actually a string, the first 8 are supposed to be numbers. Is there a way to convert each cell in the first 8 columns of a cell array from a cell containing a string, to a cell containing a double?

Upvotes: 0

Views: 223

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112749

You can do it without loops: use str2double to convert from cell array of strings to numeric array, and then num2cell to convert from numeric array to cell array of numbers:

myCell(:,1:8) = num2cell(str2double(myCell(:,1:8)));

Upvotes: 1

Benoit_11
Benoit_11

Reputation: 13945

Yes you can! It's quite easy with a for loop or using cellfun:

1:Loop 1) Let's create a cell array containing strings:

CellA = sprintfc('%d',1:9) %// Nice function to populate cell array with strings

CellA = 

    '1'    '2'    '3'    '4'    '5'    '6'    '7'    '8'   '9'

2) Loop:

for k = 1:size(CellA,2)-1

    CellA{:,k} = str2double(CellA{:,k});

end

CellA %// Display the content of CellA

CellA = 

    [1]    [2]    [3]    [4]    [5]    [6]    [7]    [8]   '9'

2: Cellfun

CellB = [cellfun(@str2double,CellA(1:end-1),'UniformOutput',false) CellA(end)]

In this case you apply str2double to all but the last elements of the cell array and then you concatenate them with the last element of CellA, i.e. the string. Both outputs are similar.

Et voilà :)

Upvotes: 1

Suneth Attygalle
Suneth Attygalle

Reputation: 179

Use the str2num function on each element of the cell in the first 8 columns to convert the strings to numbers.

Upvotes: 1

Related Questions