Loren on the Art of MATLAB

Turn ideas into MATLAB

Partitioning a Vector 9

Posted by Loren Shure,

Recently on the MATLAB newsgroup, there was a thread asking how to split up a vector into pieces which were each monotonically increasing by the value 1. The post got several answers which I did not read first. Here's my thinking.

Contents

Sample Data

Here's my sample data.

a=[2,3,4,7,9,12,13,14,15]
a =
     2     3     4     7     9    12    13    14    15

Problem and Solution

I want to break this into 4 pieces: the runs 2:4 and 12:15, plus the scalars 7 and 9. Here's how I thought about the problem.

First I want to find the runs, which are elements that differ by 1. So I calculate the differences, making sure I include the final value in the array (which is why I append a 0 below).

ad = [diff(a) == 1 0]
ad =
     1     1     0     0     0     1     1     1     0

Next, I figure out how many runs there are, by seeing how many 0 values are represented in the differences. This tells me how many arrays I will split my original array into.

numcells = sum(ad==0)
out = cell(1,numcells);
numcells =
     4

Next I find the ending indices of the chunks by looking where ad is 0. Then I start to create contents for each cell in the cell array out, starting with index 1 in the original array.

indends = find(ad == 0);
ind = 1;
for k = 1:numcells
   out{k} = a(ind:indends(k));
   ind = indends(k)+1;
end

Here's what out looks like now.

out
out{:}
out = 
    [1x3 double]    [7]    [9]    [1x4 double]
ans =
     2     3     4
ans =
     7
ans =
     9
ans =
    12    13    14    15

File Exchange Function

On the File Exchange, you can get a more general purpose function called SplitVec on SplitVec by Bruno. It does this and a whole lot more.

Do You Need to Partition Data?

If you need to partition data, I'd like to understand why, and how you do so. Let me know here.


Get the MATLAB code

Published with MATLAB® R2012b

12 views (last 30 days)  | |

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.