How to convert cell array containing text to numbers?

조회 수: 13 (최근 30일)
Abhishek Chakraborty
Abhishek Chakraborty 2021년 4월 3일
편집: Matt J 2021년 4월 3일
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?

채택된 답변

Matt J
Matt J 2021년 4월 3일
편집: Matt J 2021년 4월 3일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by