eval for string to variable

55 ビュー (過去 30 日間)
Jonathon Cheah
Jonathon Cheah 2023 年 10 月 17 日
コメント済み: Walter Roberson 2023 年 10 月 18 日
I have a GUI with a string as variable and a returned value for it.
var="simulation type"
returned GUI value:
DataEdit.Value = 1x1 cell array {'RUN 1'}
eval([var '=' char(DataEdit.Value) ';']) gives Error using eval, Argument must be a text scalar.
Any suggestions?
  2 件のコメント
Stephen23
Stephen23 2023 年 10 月 17 日
"Any suggestions?"
The fact that EVAL lets you obfuscate such buggy code should be a big hint that this should be avoided.
Walter Roberson
Walter Roberson 2023 年 10 月 17 日
And when the XML file has in it
app = ''
then should your code delete your GUI, writing over the app variable that is holding the framework of your entire GUI ?

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

採用された回答

Voss
Voss 2023 年 10 月 17 日
Since var is a string (as opposed to character vector), when you concatenate it with character vectors, those character vectors are converted to strings as well, and the result is a string array:
var="simulation type";
DataEdit.Value = {'RUN 1'};
[var '=' char(DataEdit.Value) ';']
ans = 1×4 string array
"simulation type" "=" "RUN 1" ";"
However, if you convert var into a character vector, then the concatenation works:
[char(var) '=' char(DataEdit.Value) ';']
ans = 'simulation type=RUN 1;'
You could also use the + operator for string concatenation, to concatenate everything as a string:
var + '=' + char(DataEdit.Value) + ';'
ans = "simulation type=RUN 1;"
But in either case, you cannot eval the result because simulation type is not a valid variable name:
try
eval([char(var) '=' char(DataEdit.Value) ';'])
catch ME
disp(ME.message)
end
Undefined function 'simulation' for input arguments of type 'char'.
try
eval(var + '=' + char(DataEdit.Value) + ';')
catch ME
disp(ME.message)
end
Undefined function 'simulation' for input arguments of type 'char'.
So what is it you want to do with this?
  4 件のコメント
Jonathon Cheah
Jonathon Cheah 2023 年 10 月 18 日
Hi Stephen,
I have a vey large multi layer deep xml config file for a simulator. I did a readstruct (*.xml) to start with to search the multi thread, multi layer decendents, calibration data by the GUI. The updated struct generates an identical xml file with desired values...simulator is finicky about the config.
Guess eval() is a nice hack function to have, to do this....quickly.
-jc
Walter Roberson
Walter Roberson 2023 年 10 月 18 日
What XML writing routine are you using that cares about the name of the variable holding the data to be written??
Have you considered using dynamic field names of a struct, and using writestruct to write the output XML file ? Perhaps having used readstruct to read the original in?

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by