Recursive built-in anonymous function in script

I am trying to write a recursive built-in anonymous function in a Matlab script.

Here's the MWE:

funR = @(x) [x(1) funR(x(2:end))];
funR(0:5);

But this raises the following exception:

Undefined function or variable 'funR'.

This works when it runs in a function file, but not when run in a script. This is because Matlab reads them differently.

My expected result from this MWE:

[0, 1, 2, 3, 4, 5]

How to do it right?

The goal is for funR to be defined as an inline function, so two or more linear solutions are not what I want. Please ignore if this or MWE makes sense, this is not a question of this question.

+4
source share
1 answer

, , , , , .

, , .

funR = @(x, funR) [x(1) funR(x(2:end), funR)];
funR(0:5, funR)

, - . , Mathworks, . , iif, , .

% From the article linked above
iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();

% Recurse as long as there is more than one element in x 
funR = @(x,funR)iif(numel(x) > 1,   @()[x(1), funR(x(2:end), funR)], ...
                    true,            x);

funR(0:5, funR)

, , , . , , .

+5

Source: https://habr.com/ru/post/1678406/


All Articles