Reputation: 511
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.
Upvotes: 0
Views: 85
Reputation: 24117
Create this class:
classdef mytrig
properties
x
end
methods
function out = sin(obj)
out = sin(obj.x);
end
end
end
Then at the command line:
>> A = mytrig;
>> A.x = pi;
>> A.sin
ans =
1.2246e-016
>> A.x = pi/2;
>> A.sin
ans =
1
The way you're doing it at the moment won't work, because when you create the function handle A.sin=@()sin(A.x)
, the function handle captures a copy of the current workspace, including x
, which then remains fixed afterwards, even if you subsequently change x
. If you want to be able to change x
afterwards yourself, these best way would be to be implement a class as above.
Hope that helps!
Upvotes: 1
Reputation: 21563
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.
Upvotes: 0