Search code examples
matlabfunction-handle

Matlab, function handle auto use parameter


Hi I have a question about how to achieve the following behaviour in Matlab.

A.x=pi
A.sin=@()sin(A.x)

A.sin() % Returns  1.2246e-16, essentially 0 so all good so far.

% Now for the problem
A.x = pi/2
A.sin() % Returns  1.2246e-16, meaning the new A.x is not used. It should return 1.

Does anyone have any ideas how to achieve this. I know I could define A.sin as @(x) sin(x) then provide A.x but would rather find an alternative.

Thanks.


Solution

  • Once you assign a value to a variable in Matlab, it is fixed.

    If you want to have something that is updated automatically, please look into classes.


    If you don't like classes, you could also define a function, for example

    myAsin = @()sin(A.x)
    

    Can't test it now, but as it is a function you should be getting the updated value when you call it after A.x is updated.