How to split vector according to conditions?

Hello,
I have a quite technical question concerning vectors splitting
Consider I have a vector containing groups of successive values e.g. :
V = [1 2 34 35 36 102 103 104]
This vectors contains the coordinates of another bigger vectors satisfying a specific condition
(e.g. the values of X smaller than 20: X(1) = 13, X(2) = 12, X(34) = 15, X(35) = 3, X(36) = 9, X(102) = 19, X(103) = 12, X(104) = 11)
I would like to split the vector V into (in this case 3) different parts of consecutive values (here [1 2] , [34 35 36] and [102 103 104])
in order to, then, apply a condition for each part, like for example find the smallest value of X in each of these parts (here X(2), X(35),X(104))
Do you have any ideas of how to accomplish this without using any "for" loop?
Thanks a lot!

 採用された回答

Star Strider
Star Strider 2020 年 6 月 2 日

1 投票

One approach:
V = [1 2 34 35 36 102 103 104];
d = find(diff([0 V]) > 1);
p = diff([1 d numel(V)+1]);
Out = mat2cell(V, 1, p);
V1 = Out{1} % View Output (Delete)
V2 = Out{2} % View Output (Delete)
V3 = Out{3} % View Output (Delete)
The last 3 assignments just show the results (and how to access them), and are not otherwise necessary for the code.
I am not certain how robust this is (it may need to be modified for other vectors), however it works here.

4 件のコメント

Matteo Babin
Matteo Babin 2020 年 6 月 3 日
Hi,
Thanks for your answer. But how can I do this without knowing in how many parts I can divide the vector V.
Because in this case the vector V is divided in 3 parts (V1, V2, V3), but this wouldn't work if V was for example [ 1 2 3 22 23 45 46 47 95 96] which will be divided in 4 parts. I'm looking for a solution which works for all V's in this form, not knowing beforehand in how many parts we should divide it (the problem here is V1, V2,V3).
Do you have any ideas how to do that without a for-loop?
Thanks again
Star Strider
Star Strider 2020 年 6 月 3 日
It works correctly without modification with this ‘V’ as well:
V = [ 1 2 3 22 23 45 46 47 95 96];
d = find(diff([0 V]) > 1);
p = diff([1 d numel(V)+1]);
Out = mat2cell(V, 1, p);
V1 = Out{1} % View Output (Delete)
V2 = Out{2} % View Output (Delete)
V3 = Out{3} % View Output (Delete)
V4 = Out{4}
producing:
V1 =
1 2 3
V2 =
22 23
V3 =
45 46 47
V4 =
95 96
Again, ‘V1’ through ‘V4’ simply show the result in ‘Out’, and how to access them (if you are not familiar with working with cell arrays).
Matteo Babin
Matteo Babin 2020 年 6 月 3 日
all right thank you!
Star Strider
Star Strider 2020 年 6 月 3 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2020 年 6 月 2 日

0 投票

Not exactly sure what you are trying to do.
m=[min(X(V(1:2))),min(X(V(3:5))),min(X(V(6:8)))];

カテゴリ

ヘルプ センター および 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