How to segment an array to different parts?

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!

Antworten (2)

Jos (10584)
Jos (10584) am 6 Aug. 2019

1 Stimme

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 am 6 Aug. 2019
Bearbeitet: KALYAN ACHARJYA am 6 Aug. 2019

0 Stimmen

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....

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 6 Aug. 2019

Beantwortet:

am 6 Aug. 2019

Community Treasure Hunt

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

Start Hunting!

Translated by