Help with anonymous function
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
John
el 22 de Dic. de 2014
Editada: Star Strider
el 22 de Dic. de 2014
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 comentarios
Respuesta aceptada
Star Strider
el 22 de Dic. de 2014
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 comentarios
Star Strider
el 22 de Dic. de 2014
Editada: Star Strider
el 22 de Dic. de 2014
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);
Más respuestas (0)
Ver también
Categorías
Más información sobre Whos en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!