MATLAB Answers

## How do you call a nested function?

Asked by karen

### karen (view profile)

on 18 Jun 2013
Accepted Answer by Wayne King

### Wayne King (view profile)

Hello. I understand how a nested function works, but I'm having a problem calling it in the command window. I don't know if I'm calling it wrong or not.

## Products

No products are associated with this question.

## 2 Answers

### Wayne King (view profile)

Answer by Wayne King

### Wayne King (view profile)

on 18 Jun 2013
Edited by Wayne King

### Wayne King (view profile)

on 18 Jun 2013
Accepted answer

You want to put the nested function inside another function (as the term nested implies) and then call the top-level function. As an example, create the following file, evenodd.m

```     function [even, odd] = evenodd(x)
even = evensamples(x);
odd = oddsamples(x);```
```        function even = evensamples(x)
even = x(1:2:end);
end
function odd = oddsamples(x)
odd = x(2:2:end);
end
end```

Save the above file evenodd.m in a folder on the MATLAB path and then call

``` >> x = randn(16,1);
>> [even,odd] = evenodd(x);```

Note that evenodd() calls two nested functions evensamples() and oddsamples()

### Jan Simon (view profile)

Answer by Jan Simon

### Jan Simon (view profile)

on 18 Jun 2013

You cannot call a nested function from the outside, e.g. from the command line, directly. This is the nature of a nested function. Sub-functions cannot be called directly also.

#### Join the 15-year community celebration.

Play games and win prizes!

Learn more

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

### MATLAB Academy

New to MATLAB?

Learn MATLAB today!