Create for loop to simplify code and output arrays

I have this code:
len1 = a(4);
st1 = 5; % starting index for first channel
y1 = a(st1: st1+len1-1);
len2 = a(st1+len1);
st2 = st1+len1+1; % starting index for second channel
y2 = a(st2: st2+len2-1);
len3 = a(st2+len2);
st3 = st2+len2+1; % starting index for third channel
y3 = a(st3: st3+len3-1);
len4 = a(st3+len3);
st4 = st3+len3+1;% starting index for fourth channel
y4 = a(st4: st4+len4-1);
This is taking data from a text file and outputting different values for y (i.e y2 = 1524x1 double).
I know there's a simpler for loop I can do but I can't seem to get it right! Can you help?

 채택된 답변

Esme Stanford-Durkin
Esme Stanford-Durkin 2020년 4월 28일
Solution, array to cell needed:
ch = a(1);
len = a(4);
st = 5 ;
y{1} = a(st: st+len-1);
for i = 2 : ch
len(i) = a(st(i-1) + len(i-1 ));
st(i) = st(i-1) + len(i-1) + 1 ;
y{i} = a(st(i):st(i)+len(i)-1 );
end

추가 답변 (2개)

Saurav Roy
Saurav Roy 2020년 4월 28일
Hey !
I think this is somwhat close to what you are looking for,
num = length(a);
len = a(4);st = 5;
y = a(st: st+num-1);
for i = 2 : num
len(i) = a(st(i-1) + len(i-1));
st(i) = st(i-1) + len(i-1) + 1;
y(i) = a(st(i):st(i)+len(i)-1);
end

댓글 수: 4

Hey Saurav!
Thanks for the response. So num should be the number at index 1 of a so i've changed it to num = a(1). Not that that makes a difference (there's usually 4).
I've run your code and i get this error:
Unable to perform assignment because the left and right sides have a different number of elements.
Error in realdata_st (line 42)
y(i) = a(st(i):st(i)+len(i)-1 );
Here is the updated code:
num = a(1);
len = a(4);
st = 5 ;
y = a(st: st+len-1);
for i = 2 : num
len(i) = a(st(i-1) + len(i-1 ));
st(i) = st(i-1) + len(i-1) + 1 ;
y(i) = a(st(i):st(i)+len(i)-1 );
end
Any ideas??
Saurav Roy
Saurav Roy 2020년 4월 28일
편집: Saurav Roy 2020년 4월 28일
Hey,
what exactly does 'a' represent here ?
a is an array containing all the data from the text file
a(1) is the number of 'channels' (number of y outputs), so in my initial code there would be 4 channels
a(4) contains the value of the length of the data
Then a(5) - a(5 + len-1) is the data
Then the next 'channel' will start.
If this makes sense
Found the solution!

댓글을 달려면 로그인하십시오.

Esme Stanford-Durkin
Esme Stanford-Durkin 2020년 4월 28일

0 개 추천

a is an array containing all the data from the text file
a(1) is the number of 'channels' (number of y outputs), so in my initial code there would be 4 channels
a(4) contains the value of the length of the data
Then a(5) - a(5 + len-1) is the data
Then the next 'channel' will start.
If this makes sense

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by