匿名函数中定义变量

匿名函数中定义变量

本文介绍了为什么我不能在 MATLAB 匿名函数中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定遗漏了一些非常简单的东西,因为这似乎不应该那么难.

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

这段代码是正确的:

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)

为什么会中断?我不能在函数内部定义 q ?我想使用匿名函数的全部原因是,我实际上可以在其中执行多行代码,然后返回答案.我想匿名函数的最后一条语句是返回的内容,但是如何在其中定义变量?我不想在定义匿名函数之前定义 q.

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.

谢谢.

推荐答案

不能在匿名函数中声明变量,因为它必须由表达式构造,ie:handle = @(arglist)expr

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

如果你想要可读性,在函数外定义q,像这样:

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

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

这篇关于为什么我不能在 MATLAB 匿名函数中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:35