Effacer les filtres
Effacer les filtres

Manipulating an anonymous function

6 vues (au cours des 30 derniers jours)
Will
Will le 16 Jan 2014
Commenté : per isakson le 22 Jan 2014
I have a handle class myClass which has a property myFunc that is a function handle which I define with an anonymous function, e.g.
myClass.myFunc = @(x) 2*x
Is it possible to use myFunc to redefine itself? I tried
myClass.myFunc = @(x) -myClass.myFunc(x)
but trying to evaluate this led to a max recursion error. My function is defined inside of a class method using a local variable like:
myClass.myFunc = @(x) localVar*x
Otherwise, I would consider using func2str, but that doesn't help because it produces the expression involving localVar which is no longer defined. Right now, I am using
myClass.myOtherFunc = @(x) -myClass.myFunc(x)
but I'd prefer not to have to create a separate property just for this.

Réponse acceptée

Walter Roberson
Walter Roberson le 17 Jan 2014
tmp = myClass.myFunc;
myClass.myFunc = @(x) ~tmp(x);
  3 commentaires
Walter Roberson
Walter Roberson le 17 Jan 2014
Are you sure you have the (x) after tmp ? Could you show the exact two lines of code that you use?
Will
Will le 21 Jan 2014
Sorry, your solution works for me now. I tried it before and got the error I mentioned, but maybe I had a typo somewhere.

Connectez-vous pour commenter.

Plus de réponses (1)

per isakson
per isakson le 17 Jan 2014
Modifié(e) : per isakson le 17 Jan 2014
I don't understand what you want to achieve, but
>> myc = my_class();
>> x = myc.foo(5);
>> x
x =
-10
where
classdef my_class
properties
foo1
end
methods
function this = my_class( )
this.foo1 = @(x) 2*x;
this.foo1 = @(x) -this.foo1(x);
end
function out = foo( this, val )
out = this.foo1(val);
end
end
end
  2 commentaires
Will
Will le 21 Jan 2014
That is basically what I was trying to do. If you change the first line of your class definition from
classdef my_class
to
classdef my_class < handle
you will get a max recursion error when you run myc.foo(5).
per isakson
per isakson le 22 Jan 2014
My mistake. However, this looks like a bug to me. Did you report to tech-support?

Connectez-vous pour commenter.

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by