Calling function in function
3 views (last 30 days)
Show older comments
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
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.
Accepted Answer
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)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!