Automating function creation from an input statement
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Aakash
2023년 7월 5일
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
Aakash
2023년 7월 5일
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
2023년 7월 5일
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)
추가 답변 (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
댓글 수: 0
Dyuman Joshi
2023년 7월 5일
편집: Dyuman Joshi
2023년 7월 6일
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).
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Low-Level File I/O에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!