Using strings as variable names in a for loop

16 ビュー (過去 30 日間)
John
John 2015 年 10 月 29 日
編集済み: Stephen23 2019 年 6 月 19 日
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?
  2 件のコメント
John
John 2015 年 10 月 29 日
Ok, thanks a lot for your remarks. I will study about structures and tables in Matlab as soon as I will have time to do it, for the moment I was looking only for a workaround.

サインインしてコメントする。

採用された回答

Thorsten
Thorsten 2015 年 10 月 29 日
編集済み: Thorsten 2015 年 10 月 29 日
You can use
eval(['C=zeros(' myvar ');'])
But it would be much simpler to code
k = [20, 30];
for i = 1:numel(k)
C = zeros(k(i));
end
If you need the year
year = [2006, 2007]
then k(i) is the value of year(i).

その他の回答 (1 件)

TastyPastry
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 件のコメント
John
John 2015 年 10 月 29 日
編集済み: John 2015 年 10 月 29 日
The problem is that I have several variables in the for loop whose definition and value depend on the year suffix, that is they are constructed by combaining a letter (K,g, and so on) with the year number, so that they become K2006, g2006 and so on in the first iteration, K2007, g2007 and so on in the second iteration, and I have to consider also possible more years.
So my question is: is it possible to "transform" myvar from a string to an admissible variable name?
Thorsten
Thorsten 2015 年 10 月 29 日
編集済み: Thorsten 2015 年 10 月 29 日
It's not a good idea to code your data this way. Simply define variables K, g and so on as a vector of numbers, one for each year, as I've detailed in my answer below.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by