How to group sets of data based on linearly increasing sequence into individual column vectors, and to also return indexing range of where the data set started and ended for each subvector produced from the original column vector

3 views (last 30 days)
Hello,
Lets say I have a column vector that contains data such as,
A = [5;6;7;8;9;10;52;53;54;55;84;85;86;87;88;89;90;91]
I was wondering what would be the simplest and most easy-to-understand method of returning column vectors that groups the data into sets based on their linearly increasing sequence such as,
%Preferred output would be three vectors, each containing a set of data from A:
A1 = [5;6;7;8;9;10],
A2 = [52;53;54;55],
A3 = [84;85;86;87;88;89;90;91].
And also outputs the index range where each data set/grouping started and ended in the original column vector, A, so something like (or if you have a better idea for displaying the output, feel free to share):
a = [1 6] %Since A1 began at A(1) and ended at A(6).
b = [7 10]
c = [11 18]
Does that make sense? I have MATLAB R2015a btw. Please excuse my limited MATLAB programming vocabulary as I am still learning.
Thanks in advance, and any advice would be appreciated.

Accepted Answer

Image Analyst
Image Analyst on 22 Jul 2015
This will do it:
A = [5;6;7;8;9;10;52;53;54;55;84;85;86;87;88;89;90;91]'
da = find(diff(A) ~= 1)+1
% Tack on first and last element
da = [1, da, length(A)+1]
% Make a cell array where each row represents the linear segment
% and the first column has the sub-array,
% and the second column contains the starting and ending indices
for k = 1 : length(da)-1
% First cell has the linear segments
ca{k, 1} = A(da(k) : da(k+1)-1);
% Second cell has the starting and stopping indices.
ca{k, 2} = [da(k), da(k+1)-1];
end
celldisp(ca)
In the command window:
ca{1,1} =
5 6 7 8 9 10
ca{2,1} =
52 53 54 55
ca{3,1} =
84 85 86 87 88 89 90 91
ca{1,2} =
1 6
ca{2,2} =
7 10
ca{3,2} =
11 18
If you don't know how to work with cell arrays, see the FAQ:
and
  1 Comment
George Vuong
George Vuong on 22 Jul 2015
Thanks for your help Image Analyst, much appreciated. I liked how you included a for loop to ensure that even if my column vector, A, changes in terms of value and length, the loop will take that into account and still provide what I need.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!