I have an array [ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5]. I'm trying to group the elements that are within a window of length 1, so I get [ 1 1.2 1.5 1.9] [8 8.1] [12.3 12.5] How can this be done efficiently

댓글 수: 2

Matt J
Matt J 2018년 8월 21일
Will the grouped elements always be consecutive?
how can I use the same concept to group every 4 binary digit, for the case I have an array of 256 binary number,
example
a=[1 1 1 1 1 1 1 1 1 0 1 1 1 0 0 0];
to be in a form of
b=[1111;1111;1011;1000]

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

 채택된 답변

Matt J
Matt J 2018년 8월 21일
편집: Matt J 2018년 8월 21일

1 개 추천

You could try this file
x=[ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5];
label = graph_connected_components(abs(x.'-x)<=1)
groupcell = splitapply(@(g){g},x,label)

댓글 수: 5

Amro Lulu
Amro Lulu 2018년 8월 21일
WOW, That was fast, thank you so much, it works !
Matt J
Matt J 2018년 8월 21일
Will the grouped elements always be consecutive? If so, there are faster ways.
Amro Lulu
Amro Lulu 2018년 8월 21일
yes they are always consecutive.
Amro Lulu
Amro Lulu 2018년 8월 29일
Hey Matt, I have a question related to this, what if I have a matrix x=[ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5; 1 5.3 2.1 5.4 1 6 2.1 45 23 14.3 13.4] And I need to group them the same way, however, only based on the first row, and the resulting group will include the corresponding elements from the second row, as
[ 1 1.2 1.5 1.9; 1 5.3 2.1 5.4] ..etc..
Thank you and I really appreciate it
Adapting Yuvaraj's answer,
x=[ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5; 1 5.3 2.1 5.4 1 6 2.1 45 23 14.3 13.4];
a=x(1,:);
Len=diff([0,find(diff(a)>1),numel(a)]);
S=mat2cell(x,2,Len)

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

추가 답변 (1개)

Yuvaraj Venkataswamy
Yuvaraj Venkataswamy 2018년 8월 21일
편집: Matt J 2018년 8월 21일

4 개 추천

This is your answer.
X=[ 1 1.2 1.5 1.9 5 8 8.1 10 12 12.3 12.5];
Len=diff([0,find(diff(a)>1),numel(a)]);
S=mat2cell(X,1,Len);

카테고리

도움말 센터File Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

질문:

2018년 8월 21일

댓글:

2020년 11월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by