Storing results from a for-loop in a vector of zeros
Mostrar comentarios más antiguos
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!
Respuestas (1)
Iain
el 20 de Ag. de 2014
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 comentarios
civs
el 20 de Ag. de 2014
Adam
el 20 de Ag. de 2014
Simplest way is probably just to introduce a variable separate to your loop control as e.g.
counter = 1
for i= 1001:10:n-19
...
V_min_var( counter ) = ...
...
counter = counter + 1;
end
civs
el 20 de Ag. de 2014
Adam
el 20 de Ag. de 2014
counter is just the index into your pre-allocated array so that you fill it up contiguously rather than it ending up resizing itself upto 3731 mostly zero values.
civs
el 21 de Ag. de 2014
Adam
el 21 de Ag. de 2014
Should work for all of them. Pre-allocation fills the vectors with zeros, this method just ensures that only the pre-allocated elements of the vector are then assigned values because if you call e.g.
myVector(1000) = someValue;
then myVector will be extended to size 1000 and padded with zeros if its previous size was < 1000.
civs
el 21 de Ag. de 2014
civs
el 21 de Ag. de 2014
Iain
el 21 de Ag. de 2014
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))
civs
el 21 de Ag. de 2014
Categorías
Más información sobre Portfolio Optimization and Asset Allocation en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!