Error in using eval with num2str

7 次查看(过去 30 天)
I want to rename a variable within the loop by using matlab standard eval and num2str functions.
Here is the line of the code I've written to do so:
eval(['DTU_10MW_RWT_s' num2str(seed) '_' num2str(wind) '_' num2str(I) '_' num2str(derate) ' = DTU10MWRWT;'])
When seed,wind, I, derate take integer values, the function gives what I want, but when these variables take rational noninteger values, it gives me this error:
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use brackets instead of parentheses.
Any feedback is very much appreciated.
  1 个评论
Stephen23
Stephen23 2022-8-24
编辑:Stephen23 2022-8-24
"Any feedback is very much appreciated."
In general, will converting "rational noninteger values" to text produce valid variable names? (hint: no).
For example, is the text "1.23e-4" part of a valid variable name? (hint: no, the dot and minus are not permitted).
Your data design forces you into writing complex, buggy, slow, fragile, inefficient code.
Solution: do not force meta-data into variable names.
Meta-data is data. Data should be stored in variables, not in variable names.

请先登录,再进行评论。

采纳的回答

Mathieu NOE
Mathieu NOE 2022-8-24
hello
your method works only for integers
otherwise you have to round your numbers with a given number of decimals befoe it hets converted into char but the dot character is not supported in names so I changed it to a "d" character
see example below for "seed" (other parameters are integers here for sake of simplicity) :
DTU10MWRWT = rand(1);
seed = 3*rand(1);
seed_str = num2str(1+0.01*round(seed*100)); % value rounded with 2 decimals
seed_str = strrep(seed_str,'.','d');
out_name = ['DTU_10MW_RWT_s' seed_str '_' num2str(2) '_' num2str(3) '_' num2str(4)];
eval([out_name ' = DTU10MWRWT;'])
% %% alternative to eval
%
% variableCreator ( out_name, DTU10MWRWT )
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function variableCreator ( newVar, variable )
% assignin ( 'caller', newVar, variable );
% end
%
  3 个评论
Mathieu NOE
Mathieu NOE 2022-8-24
ok - so this something I have to remember , tx !
a simple reaction when I saw the "eval" not-so-appreciated usage.
Stephen23
Stephen23 2022-8-24
编辑:Stephen23 2022-8-24
"a simple reaction when I saw the "eval" not-so-appreciated usage."
I wrote here about forcing meta-data into variable names, aka dynamic variable names. Variable names can be created dynamically using various methods and functions (e.g. EVAL, ASSIGNIN, LOAD, etc), and they all suffer exactly the same problems:

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by