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

3 vues (au cours des 30 derniers jours)
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];

Réponse acceptée

Stephen23
Stephen23 le 5 Jan 2020
Modifié(e) : Stephen23 le 5 Jan 2020
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.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by