user758077
user758077

Reputation:

Functions defined by "inline" with vector input in MATLAB

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?

Upvotes: 1

Views: 247

Answers (2)

user758077
user758077

Reputation:

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

Upvotes: 0

TroyHaskin
TroyHaskin

Reputation: 8401

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);

Upvotes: 5

Related Questions