Dante
Dante

Reputation: 796

How to get the number of anonymous function input arguments

How can I get the length of y?

>> s=10; r=28; b=8/3;
>> f = @(t,y) [-s*y(1)+s*y(2); -y(1)*y(3)+r*y(1)-y(2); y(1)*y(2)-b*y(3)];

In the above example the length is 3. Also since the t is the only independent variable, the length of y can be found by the length of the function f, that is 4 here.

EDIT

I want to write a system of differential equations solver like ode45() function. Here is an example

[t y] = ode45(f,[0 1],[1 0 0]);

Upvotes: 2

Views: 477

Answers (1)

Marcin
Marcin

Reputation: 238687

I still dont fully understand. But from the little I do undestend, it seams you want to look inside the function f, and look for y(1), y(2) or y(3) to see how many elements the y has? If this is the case you can do it as follows:

f = @(t,y) [-s*y(1)+s*y(2); -y(1)*y(3)+r*y(1)-y(2); y(1)*y(2)-b*y(3)];           
matchStr = regexp(func2str(f),'y\(\d\)','match');
numel(unique(matchStr))

This gives: 3

Basically what it does it to make f into string, and then searches for y(\d) in this string.

And just in case you want to have the number of anonymous function input arguments, than you can use:

nargin(f)

This gives: 2 (because you have t and y as inputs to f)

Upvotes: 1

Related Questions