How to extract elements form a vector in order to create an unknown number of sub-vectors?

1 回表示 (過去 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];

採用された回答

Stephen23
Stephen23 2020 年 1 月 5 日
編集済み: Stephen23 2020 年 1 月 5 日
Here is one simple approach based on diff, cumsum, and accumarray:
>> 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 ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by