Nested for loop troubles
이전 댓글 표시
Hi Everyone,
I am having difficulty troubleshooting a nested for loop. Things work fine on the first pass (when i=49) but break down on the second pass (when i=50). More specifically, instead of appending to consolFut1 on the second pass, it overwrites the data from the first pass. Can anyone spot the error? Thanks for reading.
for i = 49:52
exp=find(tifDate==expDate(i));
for j = [1; 18; 43; 63]
tifCls1 = tifCls(j:exp);
for k = [1112; 1129; 1154; 1174]
consolFut1=consolFut(k:expDateIdx(i),i);
arbTIF=tifCls1-consolFut1;
break;
end
end
end
댓글 수: 2
James Tursa
2015년 6월 29일
편집: James Tursa
2015년 6월 29일
What are the dimensions of your variables? The usual procedure is to pre-allocate an array to contain the outputs from each iteration. I assume the break statement is there for debugging, because as written it will always exit the k loop on the first iteration.
Cary
2015년 6월 30일
답변 (1개)
Image Analyst
2015년 6월 29일
0 개 추천
Nothing on the left hand side of your equations takes an index, so they all get overwritten at each iteration. Add an index if you want to store the different values.
exp is a built in function. Don't use it as the name of a variable!
댓글 수: 4
Cary
2015년 6월 29일
Image Analyst
2015년 6월 29일
consolFut1 is a 2D array. Are you trying to append a whole column to the right hand side of it? If so, then do this
consolFut1 = [consolFut1, consolFut(k:expDateIdx(i),i)]
Of course you have to make sure that the number of rows from consolFut (which is different than consolFut1 because there's no 1 at the end of it) that are specified in k:expDateIdx(i) matches the number of rows in consolFut1.
Or you could preallocate consolFut1 and then just assign a column. The thing that worries me is that k and expDateIdx(i) vary with iteration so how can we be certain that the number of rows match? In other words, that length(k:expDateIdx(i)) matches size(consolFut1, 1).
Cary
2015년 6월 29일
Walter Roberson
2015년 6월 30일
consolFut1 = [ consolFut1; consolFut(k:expDateIdx(i), i).' ];
Having multiple elements in the first dimension of the consolFut is for selecting part of a row. If you want those elements to be written into a column then you need to transpose the row to become a column.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!