Help with anonymous function
4 次查看(过去 30 天)
显示 更早的评论
I have always used a separate file for all my functions, but it's rather odd to have as many files as mathematical expressions in my code. So I am trying to used anonymous function, but I haven't been able to use them. Here is a simple example:
clc;
clear all;
a=.1;
prob = @(x) a-a*exp(-x);
y = 10*prob;
y(15)
What is the right way to fix such a code?
0 个评论
采纳的回答
Star Strider
2014-12-22
If you want to evaluate ‘prob’ at 10, it works just as with any other function. (It will pick up the value of ‘a’ from the workspace, so there is no need to pass it as a separate parameter.)
a=.1;
prob = @(x) a-a*exp(-x);
y = prob(10)
produces:
y =
99.9955e-003
Is that what you intend?
4 个评论
Star Strider
2014-12-22
编辑:Star Strider
2014-12-22
My pleasure!
Not necessarily. Let your application guide your code. I frequently let my anonymous functions pick up variables from the workspace because it makes the functions easier to write and use later, since it’s not necessary to write out a long series of arguments. That may not be appropriate in other situations.
For example, you can define your function at the beginning of your code, and then use it later in a different environment. Functions — including anonymous functions — have their own internal workspace. So for instance if you had your current code and wanted a different value for ‘a’ in ‘prob’ each time, you could have:
a = 0.1;
prob = @(x,a) a-a*exp(-x);
b = 0.5;
x = 10;
w = a*prob(x,b)
would let you pass a specific value for ‘a’ to your function in the context of its arguments, while using ‘a’ in a different context to calculate ‘w’. In this instance, ‘prob’ becomes a function of ‘x’ and ‘b’ rather than picking up ‘a’ from the workspace as previously.
So, it all depends on the context in which you want to use your function.
EDIT — I would always vectorise functions using the element-wise dot operator unless I specifically intended they always perform array operations. You can then pass vectors of arguments to them without using loops. Here, you could pass equal size vector arguments for ‘a’ and ‘x’ if you wanted to, without using a loop:
prob = @(x,a) a-a.*exp(-x);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!