How to extract elements form a vector in order to create an unknown number of sub-vectors?
조회 수: 8 (최근 30일)
이전 댓글 표시
Hello, I have a vector called M, in which there are several numbers. I need to divide it in some sub vectors (y) of different size without changing the order of the data in M. The subvector ends when it is reached a number lower than the previous. this one is the first number of the next subvector
M=[2.24;2.28;2.31;0.99;1.44;1.44;1.44;1.44;
2.12;2.25;2.48;3.61;1.86;1.89;1.89;1.89;1.89;1.89;1.89];
for j=1:(length(M(:))-1)
if M(j)>M(j+1)
else y(j)=M(1:j);
end
end
Finally I should obtain the following vectors but the code doesn't work
y1=[2.24;2.28;2.31]
y2=[0,99;1.44;1.44;1.44;1.44;2.12;2.25;2.48;3.61]
y3=[1.86;1.89;1.89;1.89;1.89;1.89;1.89];
댓글 수: 0
채택된 답변
Stephen23
2020년 1월 5일
편집: Stephen23
2020년 1월 5일
>> M = [2.24;2.28;2.31;0.99;1.44;1.44;1.44;1.44;2.12;2.25;2.48;3.61;1.86;1.89;1.89;1.89;1.89;1.89;1.89];
>> X = cumsum([true;diff(M(:))<0]);
>> C = accumarray(X,M(:),[],@(v){v});
>> C{:}
ans =
2.2400
2.2800
2.3100
ans =
0.99000
1.44000
1.44000
1.44000
1.44000
2.12000
2.25000
2.48000
3.61000
ans =
1.8600
1.8900
1.8900
1.8900
1.8900
1.8900
1.8900
You can access the contents of the cell array using indexing:
Using numbered variables is unlikely to be a good approach.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!