Problem: I have a cell array of strings
TrajLocationCompact(1, 3).locationIdCompact1
ans =
'1 1 1 1 1 32'
'29 7 1 1 2 2 2 1 1 29'
'2 1 1 2 1 1 1 1 1 1 1'
'29 29 29 39 39 29'
'29 29 37 29 29 29 29'
'29 3 2 2 1 2 1 1 1 1 1 2'
'29 3 1 1 2 1 1 2 1 2 1 29'
'3 1 1 2 1 1 2 1 1 1'
'29 29 29 29 29 29 29 29 29 1 2 2 16 5 1 1 2 1'
'29 29'
'29'
I want to trasform it in this way
'1 1 1 1 1 32' --> 1 32
'29 7 1 1 2 2 2 1 1 29' --> 29 7 1 2 1 29
'2 1 1 2 1 1 1 1 1 1 1' --> 2 1 2 1
'29 29 29 39 39 29' --> 29 39 29
'29 29 37 29 29 29 29' --> 29 37 29
'29 3 2 2 1 2 1 1 1 1 1 2' --> 29 3 2 1 2 1 2
'29 3 1 1 2 1 1 2 1 2 1 29' --> 29 3 1 2 1 2 1 29
'3 1 1 2 1 1 2 1 1 1' --> 3 1 2 1 2 1
'29 29 29 29 29 29 29 29 29 1 2 2 16 5 1 1 2 1' --> 29 1 2 16 5 1 2 1
'29 29' --> 29
'29' --> 29
Can you help me to find a regular expression that do it?

 채택된 답변

Stephen23
Stephen23 2015년 12월 11일
편집: Stephen23 2015년 12월 11일

0 개 추천

Your example indicate that you want to convert these string numbers to numeric, and then collect the runs of one value together into one element. This is easy using diff:
>> C = {'1 1 1 1 1 32','29 7 1 1 2 2 2 1 1 29'};
>> D = cellfun(@(s)sscanf(s,'%f'),C,'UniformOutput',false);
>> E = cellfun(@(v)v([true;diff(v)~=0]),D,'UniformOutput',false);
>> E{:}
ans =
1
32
ans =
29
7
1
2
1
29

댓글 수: 2

to expand on Stephen's you can write a function as such
function cellout = mycellfun(cellin)
numbers = str2num(cellin);
points = [1 find(diff(numbers)~=0)+1];
cellout = num2str(numbers(points));
end
and use it on your data
test = cellfun(@mycellfun,temp,'uniformoutput',false)
ely may
ely may 2015년 12월 14일
편집: Walter Roberson 2015년 12월 14일
I have another doubt: for example,
C = {'674 674 719 618 631 618 631 618 618 631 618 618 674 674'};
using the code I obtain [674;719;618;631;618;631;618;631;618;674]. Now I want to compact the value consecutive that are repeated one more time including them in bracket
[674;719;618;631;618;631;618;631;618;674] --> [674 719 (618 631) 618 674]
How can I do? Have I to use regolar expression?

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

질문:

2015년 12월 11일

편집:

2015년 12월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by