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

戏子无情 提交于 2019-12-13 16:35:57

问题


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.


回答1:


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

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

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



回答2:


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.




回答3:


What do you think of following construct:

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



回答4:


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.



来源:https://stackoverflow.com/questions/12229394/why-cant-i-define-a-variable-inside-a-matlab-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!