How to do a "for-loop"?

조회 수: 4 (최근 30일)
Matrix
Matrix 2023년 6월 4일
편집: VBBV 2023년 6월 4일
I have this code. My concern is in the "l" loop
for k=1:width(tt)
for l=34736:34736
recnum(l) = l;
signum(k) = k;
y{l,k} = tt.(signum(k)){recnum(l)};
end
end
then I want to change the loop "l" (until 35336)
l = 34737:34737
for k=1:width(tt)
for l=34737:34737
recnum(l) = l;
signum(k) = k;
y{l,k} = tt.(signum(k)){recnum(l)};
end
end
then
for k=1:width(tt)
for l=34738:34738
recnum(l) = l;
signum(k) = k;
y{l,k} = tt.(signum(k)){recnum(l)};
end
end
........
Finally:
for k=1:width(tt)
for l=35336:35336
recnum(l) = l;
signum(k) = k;
y{l,k} = tt.(signum(k)){recnum(l)};
end
end
As you can see, the loop "l" is changing from 34736 until 35336. Where should I put the loop properly so that I do not need to write "for-loop" until 600 times (from 34736 to 35336)?

답변 (2개)

Prannoy
Prannoy 2023년 6월 4일
You can instead insert a for loop like this :
for k=1:width(tt)
for x=34736:35336
for l = x:x
recnum(l) = l;
signum(k) = k;
y{l,k} = tt.(signum(k)){recnum(l)};
end
end
end
Unrecognized function or variable 'tt'.
This should solve your problem.

VBBV
VBBV 2023년 6월 4일
편집: VBBV 2023년 6월 4일
Hi Matrix,
What you need in this case is not for loop but a while loop which can avoid writing a loop 600 times and hence much better in terms of program execution time
for k=1:width(tt)
% define the starting point
L = 34736;
while L <= 35336
recnum(L) = L;
signum(k) = k;
y{L,k} = tt.(signum(k)){recnum(L)};
% use the increment till the count 35336
L = L + 1;
end
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by