how to generate variable name from a for loop using Portfolio function
7 views (last 30 days)
Show older comments
Hello. I need help to create my portfolio with Portfolio function with different names!
When I use this function in a for-loop then I am not able to store the different portfolio with different names!
i = length(c_1{1,:})
for x = [1:i]
% w = num2str(x)
p = Portfolio('AssetList',c_1(x,:))
% a = ['p_1_',w]
end
c_1 is a matrix with different assets in each rows, and I want for evry roes a different portfolio.
the problem is that I want to call evry portfolio in a different names, like p_1, p_2 , ecc.... But I can not do it!
Is a Problem of Portfolio function?
I need different names because after I have to add other constrains to the portfolios and calculate other moments of this portfolios!
the real aim of the code is to extract the portfolio with better mean.
If you anyone could propose a snippet of code that would be able to do this for me, it would be greatly appreciated. Thanks!
1 Comment
Stephen23
on 3 Nov 2020
"the problem is that I want to call evry portfolio in a different names, like p_1, p_2 "
Numbering variables like that is a sign that you are doing something wrong.
Forcing meta-data (e.g. pseudo-indices) into variable names is a sign that you are doing something wrong.
The simple, fast, and very efficient solution is to use indexing into one variable. You should use indexing.
Accepted Answer
Ameer Hamza
on 3 Nov 2020
Although possible using eval(), creating variable names dynamically is considered a bad coding practice: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. It will make your code hard to understand and debug. It is better to create arrays.
For example, instead of
c_1 = 1;
c_2 = 5;
create
c = [1 5]
and then access using indexing
c(1)
c(2)
0 Comments
More Answers (0)
See Also
Categories
Find more on Portfolio Optimization and Asset Allocation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!