필터 지우기
필터 지우기

How to write one universal function to evaluate many equations?

조회 수: 4 (최근 30일)
Simon
Simon 2023년 7월 2일
편집: Simon 2023년 7월 4일
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에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by