为什么不能在MATLAB匿名函数中定义一个变量? [英] Why cant I define a variable inside a MATLAB anonymous function?
问题描述
这段代码是正确的:
清除所有
无论= @(x)交易(max(x),size(x));
input = randn(1,1000);
[ab] = whatever(输入)
然而,我真正想做的是像这样:
clear all
whatever = @(x)deal(q = 3; q * max( x),大小(x));
input = randn(1,1000);
[a b] =无论(输入)
为什么这会打破?我不能在函数内定义q?我想要使用匿名函数的全部原因是我可以在其中执行多行代码,然后返回答案。我假设匿名函数的最后一个语句是返回的,但是如何在其中定义变量?我不想在匿名函数的定义之前定义q。
谢谢。
您不能在匿名函数中声明变量,因为它必须从表达式构造 ie : handle = @(arglist)expr
p如果您想要可读性, q
在函数外部,如下所示:
q = 3;
whatever = @(x)deal(q * max(x),size(x));
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, 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));
这篇关于为什么不能在MATLAB匿名函数中定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!