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!