1

Defining a function with

f = inline('x+P1*P2-P3',3);

one can calculate f(1,2,3,4), f(0,1,2,1), etc.

How should I write the function f so that I can use vectors such as 1:4 or [2,3,6,4] as an input?

  • 2
    Do you mean `f = inline('x+P1*P2-P3',3);`? What behavior do you expect? What happens now if you try `f(1:4,2,3,4)`? Also, you should be using [Anonymous Functions](https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html) instead of `inline` which is deprecated. – jodag Dec 14 '17 at 04:23
  • @jodag: Thanks for that! I put a 4 there to make sure the code works. 3 should work as well. I was trying to fix some old implementation of [numerical algorithms](https://sites.google.com/site/numericalanalysis1burden/module-7/matlab), which used that function. –  Dec 14 '17 at 12:56
  • @jodag: you are right. One should have `3` instead of `4` there if `f` has only 4 arguments. Fixed. (I didn't notice this problem until I tried to find my own answer.) –  Dec 21 '17 at 14:28

2 Answers2

5

The posted code works because of the extremely rigid structure allowed by the deprecated inline:

inline(expr,n) where n is a scalar, constructs an inline function whose input arguments are x, P1, P2, ... .

Note: "inline will be removed in a future release. Use Anonymous Functions instead."

Noting the note, you can duplicate the behavior of the posted code by doing:

f = @(x,P1,P2,P3) x+P1*P2-P3;

You can also get your desired behavior by just having an x and indexing it within the body of the anonymous function:

f = @(x) x(1)+x(2)*x(3)-x(4);
TroyHaskin
  • 8,361
  • 3
  • 22
  • 22
0

I have just learned from these two answers:

that the keyword is Comma-Separated Lists. One can simply use

f = inline('x+P1*P2-P3',3);
a = [1,2,3,4]; % or a = 1:4;
c = num2cell(a); 
f(c{:})