Use eval statement to create Matrices with variables
古いコメントを表示
I am having trouble with some seemingly basic eval syntax. I have a few variables in loops that I'd like to use to create the name of a new variable and set it equal to the result of my loop.
Here's where I've gotten so far.
eval(['SL_Excess_Fwd' '_' num2str(RtnLen(rl)) '_SL_' num2str(SL_Per(slp)) '=' SL_Excess_Fwd ]);
Gives me the error - Warning: Out of range or non-integer values truncated during conversion to character.
Error using horzcat
CAT arguments dimensions are not consistent.
When I do just the following I get the answer = SL_Excess_Fwd_5_SL_2
['SL_Excess_Fwd' '_' num2str(RtnLen(rl)) '_SL_' num2str(SL_Per(slp))]
I basically just want to simulate the command SL_Excess_Fwd_5_SL_2 = SL_Excess_Fwd;
Thanks in advance for the help, Brian
採用された回答
その他の回答 (1 件)
Matt Fig
2012 年 10 月 3 日
3 投票
Why are you using EVAL in the first place? This is usually strongly discouraged because it is slow, it is prone to bugs and strange behavior, and it makes the code hard to handle and very difficult to understand. So what is it you think you gain by using EVAL instead of using standard MATLAB variable structures?
2 件のコメント
Matt Fig
2012 年 10 月 3 日
Brian comments:
"This is part of a loop that is being done numerous times. I'd like each iteration in my nested loop to create a variable with the name of the combination that I'm on for further analysis. The variables SL_Per and Rtn_Len each have 3 different values. In the end I'd like 9 SL_Excess_Fwd variables with different names and storing the result of that iteration.
All that said, if you have a better suggestion I'd love to hear it. I hate trying to use the eval function. Speed isn't an issue because I'm only doing this 9-15 times total in my program.
Thanks, Brian"
It is common to use structures or cell arrays instead.
for ii = 1:4
SL_Per{ii} = rand(randi(10,1,2));
end
Now SL_Per is a cell array, and the kth element corresponds to the iith iteration. You access this like:
SL_Per % Look at the cell array.
SL_Per{3} % Look at the third element.
Or one could use a structure:
for ii = 1:3
for jj = 1:2
S.(sprintf('%s%i','run',ii)){jj} = rand(randi(10,1,2));
end
end
Now S is a structure. Have a look:
S % Look at the fieldnames of the structure
S.run3 % Look at the contents of field run3
S.run2{2} % Look at the second element of run2
If you have a scalar result from each run instead of an array, you could use regular arrays instead of cell arrays.
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!