How to segment an array to different parts?

42 次查看(过去 30 天)
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....

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by