Reputation: 11
I have an array of [1 1 1 1 2 2 2 3 2 3 3 3 1 1 2 2 ]
. how can I divide it to ranges which shows same numbers in one array in Matlab? I want to make matrix B which is:
B(1) = [1 1 1 1];
B(2) = [2 2 2] ;
B(3)= [3 3 3];
B(4) = [1 1];
B(5) = [2 2].
Upvotes: 1
Views: 110
Reputation: 125854
This is basically run-length encoding, the difference being you want to break the vector up into each string of repeated values instead of producing pairs of [value, nRepeats]
as is typically desired. Since your strings of repeated values have different lengths, you'll need to store them in a cell array. Here's one way to do it, using diff
, find
, and mat2cell
:
A = [1 1 1 1 2 2 2 3 2 3 3 3 1 1 2 2];
nReps = diff([0 find(diff(A)) numel(A)]);
B = mat2cell(A, 1, nReps);
This works by first computing the element-wise differences in A
with diff
. Anywhere there is a non-zero result represents a change in the value, and the index location of these non-zeroes are found with find
. Padding the ends with 0 and the length of vector A
and applying diff
again gives us the length of each string of values. The original vector A
is then broken up into a cell array using mat2cell
and these lengths.
Upvotes: 3
Reputation: 21
Set one variable as the original number, so a = array[1], then test if the next value is the same as the previous, have a counter variable attached to this. Once is it not, load into array B, and change value of that variable and do it again.
make B a 2d array
Or, look into the unqie function of matlab and use the indexes to fill B.
Upvotes: 0