Separate rows that contain certain string character

조회 수: 4 (최근 30일)
Kosta
Kosta 2017년 1월 10일
댓글: Stephen23 2017년 1월 10일
Hi all,
I would like to separate the rows of the cellarray bellow in to two cellarrays, depending on the string character on the third column, whether it ends in 'B' or 'L'.
For example, i have the cellarray:
a={
'STING ONE' 40843 '09L';
'STRING TWO' 40842 '10B';
'STRING THREE' 40841 '11L';
'STRING FOUR' 40840 '12B';
'STRING FIVE' 40839 '03L'}
I would like to split the above automatically into:
b={
'STING ONE' 40843 '09L';
'STRING THREE' 40841 '11L';
'STRING FIVE' 40839 '03L'}
and
c={
'STRING TWO' 40842 '10B';
'STRING FOUR' 40840 '12B'}
would that be possible to do?
Thanks very much in advance for your help!
Kind regards,
Kosta.

채택된 답변

Stephen23
Stephen23 2017년 1월 10일
편집: Stephen23 2017년 1월 10일
>> idx = cellfun(@(s)'B'==s(end),a(:,3));
>> c = a(idx,:)
You could even put this in a function:
>> fun = @(c)a(cellfun(@(s)c==s(end),a(:,3)),:);
>> b = fun('L');
>> c = fun('B');
  댓글 수: 2
Kosta
Kosta 2017년 1월 10일
wow.. elegant. Thanks!
Stephen23
Stephen23 2017년 1월 10일
A more efficient solution would be to run cellfun once to generate a character array of those characters:
>> vec = cellfun(@(s)s(end),a(:,3))
vec =
L
B
L
B
L
>> b = a(vec=='L',:);
>> c = a(vec=='B',:);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by