1

I'm trying to write a simple anonymous function which returns the length of an array

>> a=[1 2 3];

>> f = @() length(a);

>> f()
    3

>> a = [1 2 3 4];

>> f()
    3

Is it possible to write a function that returns the length of the updated array every time it's called?

4
  • 2
    Is there a reason you don't want a passed in as an argument? Commented Sep 10, 2017 at 21:43
  • 1
    You're just calling length in your function, so why not just use length? If you need a function handle, use f = @length;. Commented Sep 10, 2017 at 21:47
  • 1
    And did you read this section of the documentation? Commented Sep 10, 2017 at 21:48
  • @jodag: "a" can be a nested structure with many sub-fields so it would be convenient to define it just once inside the function Commented Sep 10, 2017 at 21:51

2 Answers 2

3

An ugly method to accomplish what you want

global a;
a = [1 2 3];
f = @() eval('global a; length(a)')
f()
a = [1 2 3 4];
f()

I'm compelled to say that I strongly recommend against this type of code as it relies on both globals and calls to eval, both of which should be avoided when possible.

A better method would be to pass in a as an argument to the function

a = [1 2 3];
f = @(x) length(x)
f(a)
a = [1 2 3 4];
f(a)

or, because in this case calling f is identical to calling length, then there's really no reason to use anonymous functions at all.

a = [1 2 3];
length(a)
a = [1 2 3 4];
length(a)
Sign up to request clarification or add additional context in comments.

3 Comments

Really not worth mentioning the ugly eval method, it only encourages bad practise, don't use eval when avoidable! Defining the function to take an argument is the correct answer, aside from explaining why it was previously failing (because a was static within f when f was defined in terms of a)
It depends on the constraints of the problem. If a must not be an argument then using eval may not be avoidable. If passing in a as an argument is possible then eval should not be used.
If a must not be an argument (especially in something this simple), then you've structured your code badly.
3

Defining an anonymous function in terms of a variable makes that variable static within the function. i.e.

% this...
a = [1 2 3];
f = @() length(a);
% ...  is equivalent to this...
f = @() length([1 2 3]);

You want to create an anonymous function which can take an argument

f = @(x) length(x);
a = [1 2 3]; 
f(a); % >> ans = 3
a = [1 2 3 4]; 
f(a); % >> ans = 4

Although at that point, just use length(a) and don't define some pointer-function!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.