Skip to main content
edited title
Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

array Array splitting in sub-arrays of consecutive elements

edited body
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

I want to split an array in sub-arrays of consecutive elements. For example, for the array:

a=[1 2 3 6 7 9 10 15]

a=[1 2 3 6 7 9 10 15]

I want an output 1 2 3, 6 7, 9 10, 15. I

I think that the natural choice is to use a struct for this:

[v,x] = find(diff(a)>1) %find "jumps"

xx=[0 x length(a)] 

for ii=1:length(xx)-1
   cs{ii}=a(xx(ii)+1:xx(ii+1)); %output struct array
end

v =

 1     1     1

x =

 3     5     7

xx =

 0     3     5     7     8

The code works correctly but I was wondering if there are smarter ways to do this.

I want to split an array in sub-arrays of consecutive elements. For example, for the array

a=[1 2 3 6 7 9 10 15]

I want an output 1 2 3, 6 7, 9 10, 15. I think that the natural choice is to use a struct for this:

[v,x] = find(diff(a)>1) %find "jumps"

xx=[0 x length(a)] 

for ii=1:length(xx)-1
   cs{ii}=a(xx(ii)+1:xx(ii+1)); %output struct array
end

v =

 1     1     1

x =

 3     5     7

xx =

 0     3     5     7     8

The code works correctly but I was wondering if there are smarter ways to do this.

I want to split an array in sub-arrays of consecutive elements. For example, for the array:

a=[1 2 3 6 7 9 10 15]

I want an output 1 2 3, 6 7, 9 10, 15.

I think that the natural choice is to use a struct for this:

[v,x] = find(diff(a)>1) %find "jumps"

xx=[0 x length(a)] 

for ii=1:length(xx)-1
   cs{ii}=a(xx(ii)+1:xx(ii+1)); %output struct array
end

v =

 1     1     1

x =

 3     5     7

xx =

 0     3     5     7     8

The code works correctly but I was wondering if there are smarter ways to do this.

Source Link
shamalaia
  • 294
  • 1
  • 11

array splitting in sub-arrays of consecutive elements

I want to split an array in sub-arrays of consecutive elements. For example, for the array

a=[1 2 3 6 7 9 10 15]

I want an output 1 2 3, 6 7, 9 10, 15. I think that the natural choice is to use a struct for this:

[v,x] = find(diff(a)>1) %find "jumps"

xx=[0 x length(a)] 

for ii=1:length(xx)-1
   cs{ii}=a(xx(ii)+1:xx(ii+1)); %output struct array
end

v =

 1     1     1

x =

 3     5     7

xx =

 0     3     5     7     8

The code works correctly but I was wondering if there are smarter ways to do this.