Calling function in function

3 views (last 30 days)
Raphaël
Raphaël on 6 Apr 2018
Commented: Raphaël on 6 Apr 2018
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 Comments
Rik
Rik on 6 Apr 2018
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 on 6 Apr 2018
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.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 6 Apr 2018
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)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!