Matlab- moving numbers to new row if condition is met

122 views Asked by At

I have a variable like this that is all one row:

1 2 3 4 5 6 7 8 9 2 4 5 6 5

I want to write a for loop that will find where a number is less than the previous one and put the rest of the numbers in a new row, like this

1 2 3 4 5 6 7 8 9
2 4 5 6 
5

I have tried this:

test = [1 2 3 4 5 6 7 8 9 2 4 5 6 5];
m = zeros(size(test));
for i=1:numel(test)-1;
   for rows=1:size(m,1)
     if test(i) > test(i+1);
     m(i+1, rows+1) = test(i+1:end)
   end % for rows
end % for

But it's clearly not right and just hangs.

2

There are 2 answers

0
Luis Mendo On BEST ANSWER

Let x be your data vector. What you want can be done quite simply as follows:

ind = [find(diff(x)<0) numel(x)]; %// find ends of increasing subsequences
ind(2:end) = diff(ind); %// compute lengths of those subsequences
y = mat2cell(x, 1, ind); %// split data vector according to those lenghts

This produces the desired result in cell array y. A cell array is used so that each "row" can have a different number of columns.

Example:

x = [1 2 3 4 5 6 7 8 9 2 4 5 6 5];

gives

y{1} =
     1     2     3     4     5     6     7     8     9
y{2} =
     2     4     5     6
y{3} =
     5
0
Divakar On

If you are looking for a numeric array output, you would need to fill the "gaps" with something and filling with zeros seem like a good option as you seem to be doing in your code as well.

So, here's a bsxfun based approach to achieve the same -

test = [1 2 3 4 5 6 7 8 9 2 4 5 6 5] %// Input
idx = [find(diff(test)<0) numel(test)] %// positions of row shifts
lens = [idx(1) diff(idx)] %// lengths of each row in the proposed output
m = zeros(max(lens),numel(lens)) %// setup output matrix
m(bsxfun(@le,[1:max(lens)]',lens)) = test; %//'# put values from input array
m = m.' %//'# Output that is a transposed version after putting the values

Output -

m =
     1     2     3     4     5     6     7     8     9
     2     4     5     6     0     0     0     0     0
     5     0     0     0     0     0     0     0     0