Can I make a Multidimensional Array from a 1D Array?

I have data collected in an array that I want to break up into subgroups. They are already sorted in increasing numerical order. Essentially, what I want to do is read through each point on the array and add them to the same row, but when the number in the array is >5 more than the previous, I want it to start a new row starting with that number. Is this Possible? If not, how would I go about separating the data in such a way that I formed groups of numbers that are <5 from the number before it in the array, and when the number is >5 from the previous, it forms a new grouping starting with that number?
I have some experience with Object-oriented programming with Java, but this is my first time using MatLab, so I apologize if this question is a bit outlandish.

Answers (1)

If each sequence is of a different length, then you cannot create a numeric array. You need to create a cell array. The following shows an example.
M = [rand(1,10) 6+rand(1,8) 15+rand(1,13)];
grps = cumsum([1 diff(M)>5]);
M_groups = splitapply(@(x) {x}, M, grps)
M_groups contain sequence of elements in M less than 5 apart.

Asked:

on 2 Nov 2020

Edited:

on 2 Nov 2020

Community Treasure Hunt

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

Start Hunting!