How to segment an array to different parts?

조회 수: 40 (최근 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....

카테고리

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