How do I break numeric vector into variable length sections and combine in a matrix

1 view (last 30 days)
Hi , I am trying to prep some data and I need to manipulate a vector such as the example here , A
>> A=[1,4,15,56,58,59,68,79,3,45,12,34,62,90]
A = 1 4 15 56 58 59 68 79 3 45 12 34 62 90
I want to break the vector at every point that a value is less than its preceding value and create a matrix of the smaller sections so the example above would become
B=
1 4 15 56 58 59 68 79
3 45
12 34 62 90
The problem I am having is that the length of any ascending values section of the vector A is variable but typically cannot exceed 80 values. I can find the values in the vector to break at but don't know what kind of structure to use to collect the smaller sections in one object . Matlab needs a regular m x n matrix structure or throws errors about dimensions not being consistent .
Do I need to add zeros to the sections to make each one at least as long as the longest single run of values?
B would then look something like;
B =
1 4 15 56 58 59 68 79
3 45 0 0 0 0 0 0
12 34 62 90 0 0 0 0
My coding skills fail me at this point so any help would be gratefully received. Thanks

Accepted Answer

the cyclist
the cyclist on 12 Jul 2015
Here is a straightforward method to do this. I gave the variables explanatory names, to help guide you in what I am doing:
A = [1,4,15,56,58,59,68,79,3,45,12,34,62,90];
runStarts = [1 find(diff(A)<0)+1];
numberRuns = numel(runStarts);
runLengths = diff([runStarts numel(A)+1]);
B = zeros(numberRuns,max(runLengths));
for nr = 1:numberRuns
B(nr,1:runLengths(nr)) = A(runStarts(nr):(runStarts(nr)+runLengths(nr)-1));
end
  1 Comment
AndyT
AndyT on 12 Jul 2015
Thanks so much Cyclist , I see how you have broken the problem into getting all the A sections identified first and then populating the B matrix on top of a zeros matrix. Super!

Sign in to comment.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 12 Jul 2015
Edited: Azzi Abdelmalek on 12 Jul 2015
A=[1,4,15,56,58,59,68,79,3,45,12,34,62,90]
a= diff(A)<0;
idx1=[1 find(a)+1];
idx2=find([a 1]);
n=max(idx2-idx1)+1;
m=numel(idx1);
out=zeros(m,n);
for k=1:m
ii=idx1(k):idx2(k);
out(k,1:numel(ii))=A(ii);
end
out
Or
A=[1,4,15,56,58,59,68,79,3,45,12,34,62,90]
a= diff(A)<0;
idx1=[1 find(a)+1];
idx2=find([a 1]);
n=max(idx2-idx1)+1
out=cell2mat(arrayfun(@(x,y) [A(x:y) zeros(1,n-y+x-1)],idx1',idx2','un',0))

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!