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