How to write one universal function to evaluate many equations?

6 次查看(过去 30 天)
I am working on verifying whether if equations are valid over a large data set. The challenge is that the number of equations to be verified is huge even though they are simple arithmetic equations and identities. In order to avoid writing a different function for each equation, I try to represent an equation as a 'model' and write only one universal function to eval each model. Here is a toy example to explain what I intend to do. My questions are 1.) whether if my approach is generally in right direction 2.) is there any way to avoid eval( ) in function foo( )? Thanks for your insights!
x = 7;
y = 3;
modelA = [x, y; "+", "-"];
foo(modelA)
ans = 4
z = -21;
modelB = [x, y, z; "-", "*", "=="];
foo(modelB)
ans = logical
1
function out = foo(model)
data = string(model(1,:));
operators = model(2,:);
a = strcat(operators, data);
out = eval(strcat(a{:}));
end
  15 个评论
Paul
Paul 2023-7-2
Comments can be stored using either the cell array or struct, if a cell array or struct with named fields happen to be the way to go.
C{1,1} = @(x,y,z) x - y == z;
C{1,2} = "this is the foo function";
C
C = 1×2 cell array
{@(x,y,z)x-y==z} {["this is the foo function"]}
% or
S.foo.eqn = @(x,y,z) x - y == z;
S.foo.comment = "this is the foo function";
S.foo
ans = struct with fields:
eqn: @(x,y,z)x-y==z comment: "this is the foo function"
Simon
Simon 2023-7-4
编辑:Simon 2023-7-4
@Paul I tried out your idea (structure of function handels). It works pretty well. Thanks!!

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by