How to convert cell array containing text to numbers?

9 views (last 30 days)
I have a cell array containing a mixture of numbers and letters. I want to remove all the letters and keep only the numbers in it. The cell array is:
>> A(3:12,:)
ans =
10×4 cell array
{'60E' } {'8.571307N'} {'Jun-Sep 1979'} {[9.5850e-06]}
{'61.875E'} {'8.571307N'} {'Jun-Sep 1979'} {[3.1450e-05]}
{'63.75E' } {'8.571307N'} {'Jun-Sep 1979'} {[7.1122e-05]}
{'65.625E'} {'8.571307N'} {'Jun-Sep 1979'} {[7.2475e-05]}
{'67.5E' } {'8.571307N'} {'Jun-Sep 1979'} {[9.0740e-05]}
{'69.375E'} {'8.571307N'} {'Jun-Sep 1979'} {[9.7142e-05]}
{'71.25E' } {'8.571307N'} {'Jun-Sep 1979'} {[1.1910e-04]}
{'73.125E'} {'8.571307N'} {'Jun-Sep 1979'} {[1.6324e-04]}
{'75E' } {'8.571307N'} {'Jun-Sep 1979'} {[1.6622e-04]}
{'76.875E'} {'8.571307N'} {'Jun-Sep 1979'} {[1.4362e-04]}
But I want to convert it into a numeric array containing numbers only. For example, the first 2 rows of the modified array should look like:
A=[60 8.571307 1979 9.5850e-06; 61.875 8.571307 1979 3.1450e-05];
How to do that?

Accepted Answer

Matt J
Matt J on 3 Apr 2021
Edited: Matt J on 3 Apr 2021
I don't think there is any solution that will work without any assumptions about the alphabetic content of the cells. Here, I assume that undesired text is either entirely to the left or right of the desired number in each cell:
A={'1.3E','Jun-Sep 2.6'}
A = 1×2 cell array
{'1.3E'} {'Jun-Sep 2.6'}
for i=1:numel(A)
tmp=A{i};
if ~ischar(tmp), continue; end
m=isletter(tmp);
j=find(m,1); k=find(m,1,'last');
tmp(j:k)='';
A{i}=str2double(tmp);
end
A=cell2mat(A)
A = 1×2
1.3000 2.6000

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!