Using strings as variable names in a for loop
15 次查看(过去 30 天)
显示 更早的评论
What I would like to do is:
K2006=20;
k2007=30;
years={'2006','2007'}
for i = 1:2
mystr=strcat('K',years{i})
myvar=genvarname(mystr)
C=zeros(myvar)
...
end
But the last command does not work, I get an error message saying:
Error using zeros Trailing string input must be a valid numeric class name.
Can anybody help me to fix it?
采纳的回答
更多回答(1 个)
TastyPastry
2015-10-29
Have you tried stepping line by line using the debugger? You'll notice that in the line
C=zeros(myvar);
You're trying to create a vector of zeros with 'myvar', which is a string. You can't call zeros() with a string input.
Why don't you just create a cell array which holds K2006, K2007 and their respective values? That way, you can just loop through the cell array.
2 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!