Help with anonymous function

11 visualizzazioni (ultimi 30 giorni)
John
John il 22 Dic 2014
Modificato: Star Strider il 22 Dic 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?

Risposta accettata

Star Strider
Star Strider il 22 Dic 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 Commenti
John
John il 22 Dic 2014
Great, thank you. Is it a best practice to write a function having every parameter as an argument?
Star Strider
Star Strider il 22 Dic 2014
Modificato: Star Strider il 22 Dic 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);

Accedi per commentare.

Più risposte (0)

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by