How do I turn string "C = A*B" to "data.C = data.A.*data.B " while the equation and variables may change?
2 次查看(过去 30 天)
显示 更早的评论
I'm building a GUI that reads simple formulas from an Excel file, then evaluate them as Matlab code. For example, the user may write "C=A*B" in an Excel cell, then Matlab will import the table and calculate a new variable C with the function eval. The problem is, the variables A and B are actually variables in a table, so the correct code should have been "data.C = data.A.*data.B ". The goal is to let the user create new variables without building a complicated calculator GUI.
The difficult part is, the names (A, B, C) are dynamic and there can be all sort of equations like "A=B+C/D" or "A=B^2-C". The name of the table itself is however fixed. How can I achieve that?
0 个评论
采纳的回答
Voss
2022-6-27
编辑:Voss
2022-6-27
Maybe this is worth a try:
% example usage
fix_formula("C=A*B")
fix_formula("A=B+C/D")
fix_formula("A=B^2-C")
% running it on a table
A = [1;2;3];
B = [4;5;6];
C = [7;8;9];
D = [10;11;12];
data = table(A,B,C,D)
eval(fix_formula("C=A*B"))
eval(fix_formula("A=B+C/D"))
eval(fix_formula("A=B^2-C"))
function str = fix_formula(str)
str = regexprep(str,'\<([A-Za-z_]+)\>','data.$1'); % prepend variable names with "data."
str = regexprep(str,'([*/^\\])','.$1'); % replace operators *, /, ^, \ with .*, ./, .^, .\ (element-wise)
end
更多回答(1 个)
dpb
2022-6-27
If the table name is fixed, then it's easy -- use dynamic field names as explained in accessing data in tables -- and specifically using variables for table variable names at <<Access-data-in-a-table>
4 个评论
Steven Lord
2022-6-27
There are a few functions in MATLAB that may be able to help you like symvar, vectorize, and str2func.
s = 'A=B+C/D';
sides = split(s, '=');
lhs = sides{1}
rhs = sides{2}
listOfVariablesOnRight = symvar(rhs);
str = "@(" + join(listOfVariablesOnRight, ', ') + ") " + vectorize(rhs)
fh = str2func(str)
Now call the function handle with the appropriate inputs and store the output in a field of a struct array.
result.(lhs) = fh(1, 2, 3)
check = 1 + (2/3)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!