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

조회 수: 4 (최근 30일)
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

채택된 답변

the cyclist
the cyclist 2015년 7월 12일
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
AndyT
AndyT 2015년 7월 12일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 12일
편집: Azzi Abdelmalek 2015년 7월 12일
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))

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by