3
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 27, 2017 at 9:40
\$\endgroup\$
1
  • \$\begingroup\$ You're using a cell array, not a struct. \$\endgroup\$ Commented Dec 10, 2017 at 2:22

2 Answers 2

4
\$\begingroup\$

You should preallocate the cs cell array:

[v,x] = find(diff(a)>1); %find "jumps"
xx = [0 x length(a)];
cs = cell(length(a)+1,1);
for ii = 1:length(xx)-1
 cs{ii} = a(xx(ii)+1:xx(ii+1));
end

Style comments:

  • Try to keep consistent formatting, either put spaces around all equal signs, or around none.

  • Terminate statements with a semicolon to prevent your function producing output to the command window.

answered Dec 10, 2017 at 2:34
\$\endgroup\$
0
\$\begingroup\$

You could take advantage of accessing array's elements via colon notation. For example, if you need to extract the first three elements of an array a=[7 9 6 4 5 8], you type b=a(1:3). These statements are equivalent a(1:1:3)=a(1:3)=a([1 2 3]) which return the first three elements. In your example, it is a matter of controlling the indexes for colon notation, therefore,

a=[1 2 3 6 7 9 10 15];
b=a(1:3) % --> [1 2 3]
c=a(4:5) % --> [6 7]
d=a(6:7) % --> [9 10]
e=a(end) % --> [15]
answered Dec 18, 2017 at 5:14
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.