Automating function creation from an input statement
显示 更早的评论
Hello,
I am want to have a program in which I insert N equations with N variables and it itself produces N functions of the equations.
The psuedo code woud be something like this:
Input:
Equations: Equation1: x1^2+3*x2+3, Equation2: exp(x1+x2)
Output:
function f = f(x1,x2)
f = x1^2+3*x2+3
end
function g = g(x1,x2)
g = exp(x1+x2)
end
采纳的回答
更多回答(2 个)
Swastik Sarkar
2023-7-5
You can use symvar to extract the variables in an equation, and then also use anonymous functions for the equations
The code will look something like this:
function generate_functions(equations)
% Create N anonymous functions based on the given equations
% Get the number of equations (N)
N = numel(equations);
% Create a cell array to store the functions
functions = cell(1, N);
% Loop through each equation and create an anonymous function
for i = 1:N
% Extract the equation from the input
equation = equations{i};
disp(equation)
% Extract the variables from the equation
variables = symvar(equation);
% Create a cell array of variable names as strings
variable_names = arrayfun(@char, variables, 'UniformOutput', false);
% Create an anonymous function based on the equation
input_args = strjoin(variable_names, ', ');
functions{i} = str2func(['@(', input_args, ') ', equation]);
end
% Display the generated functions
for i = 1:N
fprintf('function %s = %s(%s)\n', char(96 + i), char(96 + i), input_args);
fprintf('%s = %s\n', char(96 + i), equations{i});
fprintf('end\n\n');
end
% Return the cell array of functions (optional)
% You can use these functions later in your code
% if you want to evaluate them for specific values of the variables.
% Example: f_val = functions{1}(x1_value, x2_value, ...);
end
>> equations = {'x1^2+3*x2+3', 'exp(x1 + x2)'};
>> generate_functions(equations)
x1^2+3*x2+3
exp(x1 + x2)
function a = a(x1, x2)
a = x1^2+3*x2+3
end
function b = b(x1, x2)
b = exp(x1 + x2)
end
An efficient approach -
%Input, in the form of cell-strings
%Note that I have added an extra element
eqns = {'x1^2+3*x2+3', 'exp(x1+x2)', 'sin(x1)+x2^3*log(x3)-x4'};
%Names you want to put for the functions
names = {'f', 'g', 'h'};
%Generating function files via loop
for k=1:numel(eqns)
z = str2sym(eqns{k});
matlabFunction(z,'File',names{k});
end
This generates function files in the current directory, each function file corresponding to each element of input, i.e. eqns variable.
In case you don't want to store the function in the file, use this instead -
n = numel(eqns);
out = cell(n,1);
for k=1:numel(eqns)
z = str2sym(eqns{k});
out{k} = matlabFunction(z);
end
out
Also, @Fernando, you should avoid using the same names for the output variables and the function name (as you have done in the examples posted above).
类别
在 帮助中心 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!