Clear Filters
Clear Filters

How to write one universal function to evaluate many equations?

2 views (last 30 days)
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; "+", "-"];
ans = 4
z = -21;
modelB = [x, y, z; "-", "*", "=="];
ans = logical
function out = foo(model)
data = string(model(1,:));
operators = model(2,:);
a = strcat(operators, data);
out = eval(strcat(a{:}));
Paul on 2 Jul 2023
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 = 1×2 cell array
{@(x,y,z)x-y==z} {["this is the foo function"]}
% or = @(x,y,z) x - y == z; = "this is the foo function";
ans = struct with fields:
eqn: @(x,y,z)x-y==z comment: "this is the foo function"
Simon on 4 Jul 2023
Edited: Simon on 4 Jul 2023
@Paul I tried out your idea (structure of function handels). It works pretty well. Thanks!!

Sign in to comment.

Answers (0)




Community Treasure Hunt

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

Start Hunting!