Calling function in function

조회 수: 3 (최근 30일)
Raphaël
Raphaël 2018년 4월 6일
댓글: Raphaël 2018년 4월 6일
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)
  댓글 수: 1
Raphaël
Raphaël 2018년 4월 6일
Thank you that would work.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by