Storing results from a for-loop in a vector of zeros
조회 수: 1 (최근 30일)
이전 댓글 표시
I have the code Backtesting_10day_II (here attached).
From line 23-26 I created 4 vectors (of zeros) to pre-allocate the results from the for-loop, each of these results is the value of a portfolio calculated every 10 days (V_min_var, V_eff_var, V_min_ES, V_eff_ES).
Now in the for loop: i goes from 1001 until 3721, there are 273 iterations (n= 3740 and i=1001:10:n-19), so thinking logically there should be only 274 results per portfolio (274 values per portfolio), which means that each pre-allocating vector should be of size 274x1.
After I run the program I checked the pre-allocating vectors and I found that they were size 3731x1, the majority of the numbers were zeros (zeros from row 1 to 1000,then actual values at rows 1001,1011,1021,1031,etc until 3731, but everything in between is zero). I don't understand this because I predefined these vectors to be of size 274x1.
Why do I have so many zeros in between my results? and how can I fix this? I only need the results not the zeros in between.
Thanks!
댓글 수: 0
답변 (1개)
Iain
2014년 8월 20일
Indexing in matlab is done from a base of one.
So,
A(3479) = 1;
will change the 3479th element of A to 1.
You need to change how you are indexing your variables with the iteration number, rather than the loop variable. - How you manage that is up to you.
댓글 수: 10
Iain
2014년 8월 21일
You are confusing "value" for "index".
You must always address vectors with an index. An index can be related to a value by a simple algorithm (eg (i-991)/10 ), or by finding a value's position in a list (find(x == 45,1))
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!