How to take only first part of the string

조회 수: 1 (최근 30일)
Kanakaiah Jakkula
Kanakaiah Jakkula 2017년 9월 30일
편집: OCDER 2017년 9월 30일
Hi,
I have cell matrix as below:
column1 column2 column3
HaH 16 years 14
Tay 23 23 s
YAH 24 % shift
In column2~3, I only want to take first part if it is mixed string, my desired output:
HaH 16 14
Tay 23 23
YAH 24 shift

답변 (2개)

Cedric
Cedric 2017년 9월 30일
편집: Cedric 2017년 9월 30일
Assuming that all cells content is of class char:
B = [A(:,1), cellfun(@(s)regexp(s, '\S+', 'match', 'once'), A(:,2:3), 'UniformOutput', false)] ;

OCDER
OCDER 2017년 9월 30일
편집: OCDER 2017년 9월 30일
If dealing cell array with only strings:
A = {
'HaH' '16 years' '14';
'Tay' '23' '23 s';
'YAH' '24 %' 'shift'};
B = cellfun(@(x) sscanf(x, '%s', 1), A, 'uniformoutput', false); %scan every cell for 1st part
B =
'HaH' '16' '14'
'Tay' '23' '23'
'YAH' '24' 'shift'
If you also want to convert string part to a number ( ex: '24' to [24] )
Bnum = cellfun(@(x) sscanf(x, '%d', 1), B, 'uniformoutput', false); %scan every cell for 1st double number
NonEmptyIdx = ~cellfun(@isempty, Bnum); %mark where the numbers are in the cell
B(NonEmptyIdx) = Bnum(NonEmptyIdx); %replace string with number
B =
'HaH' [16] [ 14]
'Tay' [23] [ 23]
'YAH' [24] 'shift'

카테고리

Help CenterFile Exchange에서 Labels and Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by