Calling function in function

4 次查看(过去 30 天)
Hi, Sorry for the bad title, I don't know how to explain it in a few words.
Here is what I want to do. I have several test equations. I thought of two ways to call them :
% 1. Using variables
syms x1 x2 x3
f1=@x1+x2.^2;
f2=@3*x1+x2.^2-x3;
f3=@[x1; x2+x3]; %Out put is a vector
% ...
% or
% 2. Using funtions
function y = f1(x1,x2)
y = x1+x2.^2;
end
function y = f2(x1,x2,x3)
y = 3*x1+x2.^2-x3;
end
...
Now, I'm using another function that will be calling one of those previous equation. Let's say :
function output = step(equation,x,a,b,c)
% x is going to be a vector counting my different x1, x2 and x3. It is of the right length for the right equation.
output = equation(x)*a+b+c;
end
I would like to use a name for equation to call the right equation in my function step without having to rewrite it. Also, my x need to be able to be multple variables. How would you people write that?
Thanks and have a nice day.
  2 个评论
Rik
Rik 2018-4-6
You can use varargin to allow a varying number of input arguments. The documentation will undoubtedly give some examples.
I don't know what you are trying to do in that first option with syms, so if that is important, please elaborate. Also, you shouldn't name your functions step, it will shadow the internal function (or not), which may result in unexpected outputs or errors that are difficult to debug.
Raphaël
Raphaël 2018-4-6
No that's not my problem. I'm calling a certain function (or an equation) in my function step. I don't want to go back and edit function step each time I run it for a different equation.
The syms is for calling one of my equations. I can either call it using a function or by using syms and naming it f1. As long as I can call different equations in function step without having to re edit the whole file. Thanks anyway.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2018-4-6
f1=@(x) x(1)+x(2).^2;
f2=@(x) 3*x(1)+x(2).^2-x(3);
f3=@(x) [x(1); x(2)+x(3)]; %Out put is a vector
Now you can call
step(f2, x, a, b, c)

更多回答(0 个)

标签

Community Treasure Hunt

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

Start Hunting!

Translated by