Use eval statement to create Matrices with variables
15 views (last 30 days)
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
Jan on 3 Oct 2012
Edited: Jan on 3 Oct 2012
What is "SL_Excess_Fwd"? If it is not a string, but contains non-integer floating point values, the conversion fails here with the posted error message:
Name = ['SL_Excess_Fwd' '_' num2str(RtnLen(rl)) '_SL_' num2str(SL_Per(slp))];
eval([Name, '=', SL_Excess_Fwd])
Here the -1 cannot be converted to a CHAR value unequivocally.
I think you want:
eval([Name, '=', 'SL_Excess_Fwd']) % Quotes around the variable!
As Matt Fig has already mention, such problems are typical, when you use EVAL. It would be much smarter to use an index as index, instead of hiding it in the name of the variable:
SL_Excess_Fwd(RtnLen(rl)).SL(SL_Per(slp)) = SL_Excess_Fwd
Or at least a dynamic fieldname:
SL_Excess.sprintf('Fwd%d', RtnLen(rl)).sprintf('SL%d', SL_Per(slp)) = SL_Excess_FWD;
More Answers (1)
Matt Fig on 3 Oct 2012
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?