How to segment an array to different parts?

128 ビュー (過去 30 日間)
Ezra Raphael
Ezra Raphael 2019 年 8 月 6 日
回答済み: Jos (10584) 2019 年 8 月 6 日
Say I have an array:
a = [2,20,2,10,10,10,10,9,10,3,18,3]
I don't have the skills yet to know how to separate this into different segments that consists of three values each in a for-loop like:
segment_1 = [2,20,2]
segment_2 = [10,10,10]
segment_3 = [10,9,10]
segment_4= [3,18,3]
So the first time the loop is started, it will select the indexes of 1,2,3. Second time will result in indexes of 4,5,6.
I have only started doing
for k = 1:4
Can anyone help me with the coding? Thank you!

回答 (2 件)

Jos (10584)
Jos (10584) 2019 年 8 月 6 日
First of all, do not create separate variabeles for things that are related. A solution using cell arrays (like Kalyan does in his answer) where each segment gets its own index is far more convenient!
Another solution in your case is to store each segment of the vector a in a separate row of a 2D matrix. This requires some RESHAPE-ing.
a = [2,20,2,10,10,10,10,9,10,3,18,3]
segment = reshape(a, 3, []).
Try to play around with this, seeing what, for instance the .' (= transpose) does.

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 8 月 6 日
編集済み: KALYAN ACHARJYA 2019 年 8 月 6 日
a = [2,20,2,10,10,10,10,9,10,3,18,3]
segment_data=cell(1,length(a)/3)
l=1;
for i=1:3:length(a)-3
segment_data{l}=a(i:i+2);
end
Access data
>> segment_1=segment_data{1}
segment_1 =
10 9 10
...so on....

カテゴリ

Find more on Matrices and Arrays in Help Center and File Exchange

製品

Community Treasure Hunt

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

Start Hunting!

Translated by