Cell conversion to double
Afficher commentaires plus anciens
Greetings, Let's say a is a 11x1 cell like this a = '0.000000' '1.000000' '2.000000' '3.000000' '4.000000' '5.000000' '6.000000' '7.000000' '8.000000' '9.000000' '10.000000' and I want to convert it in double. If I try b=cell2mat(a), I got the following error : ??? Error using ==> cat CAT arguments dimensions are not consistent. Error in ==> cell2mat at 85 m{n} = cat(1,c{:,n}); However, I know I can bypass it with a loop with 2 conversion as: for i = 1:length(a) b(i) = str2num(cell2mat(a(i))); end Thus, I wonder if there is a simpler way to do this with an easy one-step function. Regards, Steven
3 commentaires
Barry Swindler
le 30 Mai 2016
Modifié(e) : Barry Swindler
le 30 Mai 2016
not sure if you found an answer yet, but a simple thing like this works.
m=zeros(size(a,1),size(a,2));
m=str2double(a);
still not just one step, but there's no need for a loop.
hope this helps!
ayesha abbassi
le 24 Fév 2018
B = cell2mat(A). now check its type by writing whos B in command window
Chrysi K.
le 5 Fév 2019
@ayesha abbassi Thank you so much!!! You helped me!!! I had a similar problem!
Réponse acceptée
Plus de réponses (1)
Daniel Shub
le 17 Oct 2011
It appears your cell array contains strings and not numbers (doubles).
b = cellfun(@(x)str2double(x), a);
6 commentaires
Fangjun Jiang
le 17 Oct 2011
Believe it or not, you can use str2double directly.
a={'1','2'};
str2double(a)
Daniel Shub
le 17 Oct 2011
Wow, another reason to like str2double over str2num.
Jan
le 17 Oct 2011
cellfun(@str2double, C) is faster than str2double(C). Surprising!
Jan
le 17 Oct 2011
"cellfun(@str2double, C)" is faster than "str2double(C)". Surprising! But the indirection "cellfun(@(x)str2double(x), C)" wastes time.
Fangjun Jiang
le 17 Oct 2011
+1, For none-time-critical task, I still vote for using str2double().
hello_world
le 4 Juil 2018
Modifié(e) : Walter Roberson
le 13 Déc 2025
@Daniel Shub: It converts all cell entries (which are string) into NaN values. I have raised a question at: https://www.mathworks.com/matlabcentral/answers/408675-how-to-convert-a-csv-file-of-cell-array-type-to-double
Can you please look into that?
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!