Manipulating an anonymous function

조회 수: 2 (최근 30일)
Will
Will 2014년 1월 16일
댓글: per isakson 2014년 1월 22일
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.

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

per isakson
per isakson 2014년 1월 17일
편집: per isakson 2014년 1월 17일
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
Will
Will 2014년 1월 21일
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 2014년 1월 22일
My mistake. However, this looks like a bug to me. Did you report to tech-support?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Function Handles에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by