필터 지우기
필터 지우기

Why won't this for loop move to the next variable?

조회 수: 1 (최근 30일)
Cary
Cary 2015년 6월 30일
댓글: Star Strider 2015년 6월 30일
On the first pass, everything is fine. i = 49, j = 1, k = 1112. On the second pass, i and j move to the next variables (50 and 18), but k stays at 1112. It does the same thing on the third and fourth pass. Can someone please point out my error? My sincerest gratitude for reading.
for i = 49:52
expiry=find(vifDate==expDate(i));
for j = [1; 18; 43; 63]
vifCls1 = vifCls(j:expiry);
for k = [1112; 1129; 1154; 1174]
consolFut1 = consolFut(k:expDateIdx(i),i);
arbVIF=vifCls1-consolFut1;
end
end
end

답변 (2개)

Thorsten
Thorsten 2015년 6월 30일
편집: Thorsten 2015년 6월 30일
I you code only i cycles to the values 49,50, ..., while j and k are always a 4x1 vector [1; 18; 43; 63] and k = [1112; 1129; 1154; 1174]. You have to use row vectors in the for loop:
for j = [1 18 43 63]
% some code
for k = [1112 1129 1154 1174]

Star Strider
Star Strider 2015년 6월 30일
Your loops probably are incrementing, but because of the way you created your indices, you’re just not seeing it.
Consider:
ix = 1;
for i = 49:52
for j = [1; 18; 43; 63]'
for k = [1112; 1129; 1154; 1174]'
Q(ix,:) = [i j k];
ix = i + 1;
end
end
end
figure(1)
stem3(Q(:,1), Q(:,2), Q(:,3))
grid on
xlabel('i')
ylabel('j')
zlabel('k')
The plot shows that all the loops are incrementing.
  댓글 수: 2
Thorsten
Thorsten 2015년 6월 30일
편집: Thorsten 2015년 6월 30일
Your example works because you use row vectors for the indices (or transposed column vectors, to be more precise). Cary's code does not work, because she uses column vectors; it is not a matter of "not seeing it".
Star Strider
Star Strider 2015년 6월 30일
The column vectors quite definitely do not work (that I found surprising).
I transposed them to demonstrate that even if the loops would increment, it will be difficult to see the result because of the inefficient ways the loops are indexed.

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

카테고리

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