简体   繁体   中英

Why cant I define a variable inside a MATLAB anonymous function?

I must be missing something really simple because this doesnt seem like it should be this hard.

This code is correct:

clear all
whatever = @(x) deal(max(x), size(x));
input = randn(1,1000);
[a b] = whatever(input) 

However, what I really want to do is something like this:

clear all
whatever = @(x) deal(q = 3; q*max(x), size(x));
input = randn(1,1000);
[a b] = whatever(input)    

Why does this break? I cant define q inside the function?? The whole reason I want to use anonymous functions is so that I can actually do multiple lines of code within them, and then return an answer. I suppose the last statement of an anonymous function is what is returned, but how do I define variables within them? I dont want to define q before the definition of the anonymous function.

Thanks.

You cannot declare variables inside an anonymous function, because it must be constructed from an expression, ie : handle = @(arglist)expr

If you want readability, define q outside the function, like this:

q = 3;
whatever = @(x) deal(q * max(x), size(x));

You don't. Anonymous functions have only a single statement. You use subfunctions for that (not a nested function, those are sick things with strange scoping rules).

function whatever = not_anonymous (x)
  % your code here
end

If you need to pass function handles, you can just use @not_anonymous .

What do you think of following construct:

tmpfun = @(x,q) deal...
whatever = @(x) tmpfun(x,3)

I'm pretty sure deal can't take in multiple commands. Multiple parameters, sure, but you're trying to pass in commands. Would this work?

whatever = @(x) q=3; deal(q*max(x), size(x));

Also, why wouldn't you just have this?

whatever = @(x) deal(3*max(x), size(x));

If you're going to define it within the function, you might as well just put the actual value there, if you can't get anything else to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM