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?

3
  • 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 instead of inline which is deprecated. Commented Dec 14, 2017 at 4: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, which used that function. Commented Dec 14, 2017 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.) Commented Dec 21, 2017 at 14:28

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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{:})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.