MATLAB Answers

Extracting text from a cell

40 views (last 30 days)
joseph Frank
joseph Frank on 24 Jul 2013
A='00003H102'
How can I write a code to extract the first 6 letters and numbers. i.e. I want B='00003H';

  1 Comment

Jan
Jan on 24 Jul 2013
@joseph: From the comments later on we see, that your data are not A='00003H102', but that you talk of a cell string. Please care for posting the real input data, because posting wrong answers for wrong inputs wastes your and our time. Thanks.
What is the wanted result, when the string has less than 6 characters?

Sign in to comment.

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 24 Jul 2013
Edited: Azzi Abdelmalek on 24 Jul 2013
A='00003H102'
A(1:6)
If you have a cell array
A={'00003H102','00003H103','00003H104'}
B=cellfun(@(x) x(1:6),A,'un',0)

  5 Comments

Show 2 older comments
Narges M
Narges M on 24 Jul 2013
ofcourse there is. have 6 be a variable: var = 6. then use an if-statement to change the value in var, in case the length of the current row is less than 6.
Azzi Abdelmalek
Azzi Abdelmalek on 24 Jul 2013
Yes it's possible
Azzi Abdelmalek
Azzi Abdelmalek on 24 Jul 2013
A={'00003H102','00003H103','00003H104','00003'}
idx=cellfun(@(x) min(numel(x),6),A,'un',0)
B=cellfun(@(x,y) x(1:y),A,idx,'un',0)

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 24 Jul 2013
A={'00003H102','00003H103','00003H104','00003' []}
B=cellfun(@(x) x(1:min(numel(x),6)),A,'un',0)

  0 Comments

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 24 Jul 2013
Edited: Andrei Bobrov on 24 Jul 2013
B = regexp(A,'^.{0,6}','match')
B = cat(1,B{:});

  0 Comments

Sign in to comment.

Tags