Automating function creation from an input statement

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Aakash
Aakash il 5 Lug 2023
To create a program that takes N equations with N variables and produces N functions based on those equations, you can use the concept of anonymous functions in MATLAB. Here's an example of how you can achieve this:
% Example input equations
equations = {'x1^2+3*x2+3', 'exp(x1+x2)'};
% Create N functions based on the equations
N = numel(equations);
functions = cell(1, N);
for i = 1:N
% Create anonymous function using eval and str2func
functions{i} = str2func(['@(x1, x2) ' equations{i}]);
end
% Example usage of the generated functions
x1 = 2;
x2 = 3;
% Evaluate the functions at the specified values
results = zeros(1, N);
for i = 1:N
results(i) = functions{i}(x1, x2);
end
  4 Commenti
Aakash
Aakash il 5 Lug 2023
Then you can modify the for loop as follows:
for i = 1:N
% Extract variables from the equation string
equation = equations{i};
variables = regexp(equation, 'x\d+', 'match')
% Create symbolic expression using str2sym
symExpression = str2sym(equation)
% Create anonymous function using matlabFunction
functions{i} = matlabFunction(symExpression, 'Vars', sym(variables))
end
x = [2, 3, 4]; % Values for x1, x2, x3
% Evaluate the functions at the specified values
results = zeros(1, N);
for i = 1:N
equation = equations{i};
variables = regexp(equation, 'x\d+', 'match')
xValues = num2cell(x(1:numel(variables)));
results(i) = functions{i}(xValues{:});
end
Dyuman Joshi
Dyuman Joshi il 5 Lug 2023
Extracting the variables and specifying them as input to matlabFunction() is not necessary, as matlabFunction automatically does that for you -
%(x2,x3) instead of (x1,x2)
y = 'x2^2+3*x3+3';
z = str2sym(y);
out = matlabFunction(z)
out = function_handle with value:
@(x2,x3)x3.*3.0+x2.^2+3.0

Accedi per commentare.

Più risposte (2)

Swastik Sarkar
Swastik Sarkar il 5 Lug 2023
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

Dyuman Joshi
Dyuman Joshi il 5 Lug 2023
Modificato: Dyuman Joshi il 6 Lug 2023
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.
You can also specify many others options, check out matlabFunction documentation for more info.
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
out = 3×1 cell array
{ @(x1,x2)x2.*3.0+x1.^2+3.0} { @(x1,x2)exp(x1+x2)} {@(x1,x2,x3,x4)-x4+sin(x1)+x2.^3.*log(x3)}
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).

Tag

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by