storing data from while loop

1 view (last 30 days)
shobhit mehrotra
shobhit mehrotra on 26 Jan 2015
Answered: Guillaume on 26 Jan 2015
Hello, I'm trying to sort the data from vector AA such that if AA(n+1) > AA(n) it'll store the indices into a matrix {data} if theres a break, (AA(N+1) < A(n)) data in AA will occupy a new column
This is the code I got for so far, however the {data} matrix is empty
AA = [ 1 2 3 5 7 10 9 11 13 14 17 19 17 22 25];
data = {};
k =1;
while true
idx = find (AA < AA - 1, 1);
if ~isempty (idx);
data{k} = AA(1:idx-1);
AA = AA(idx:end);
k = k + 1;
else
data {k} = AA(1:end);
break
end
end
The final result should be the matrix {data} contains the following
cell 1x1: [1 2 3 5 7 10]
cell 1x2: [11 13 14 17 19]
cell 1x3: [22 25]
Thanks!

Accepted Answer

Guillaume
Guillaume on 26 Jan 2015
Assuming you made a typo and cell{3} should be [17 22 25]:
AA = [ 1 2 3 5 7 10 9 11 13 14 17 19 17 22 25];
data = mat2cell(AA, 1, diff([0 find(diff(AA) < 0) numel(AA)]))
Basically, find the length of the runs, using diff and find and use mat2cell to convert to cell.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!