问题
I'm asking this question to test a concept. I'm not trying to have a solution presented in code, I simply need advice as to what direction to continue.
I would like to make a structure field that is always a function of other fields of the same structure.
I have been able to implement code that can modify the existing structure and update it with a new field. But this doesn't work without re-initializing a code this is not ideal.
I need the ability to add another structure, give it values for certain fields, then automatically update the rest of the fields via functions I have defined.
Is a structure even the right method to accomplish this task? I think it isn't but I am not sure what method can be used.
I've attached a very simple code snippet to demonstrate the problem.
module = struct('dim', [ 3 1 0.05], ...
'point', [0 0 0], ...
'shape', cubeshape(module.dim,module.point))
% cubeshape is my function of dim & point
matlab returns an error....
Undefined function or variable 'dim'.
this makes sense because the struct() function has not yet been closed which means that the module struct has not yet been defined.
If my question is too novice, please just tell me I can continue to research, but some guidance would be appreciated.
Thanks!
回答1:
You can set the 'shape'
field to a function handle:
module = struct('dim', [3 1 0.05], ...
'point', [0 0 0], ...
'shape', @()cubeshape(module.dim,module.point))
And then access the value of the 'shape'
field via
module.shape()
However, you'll find that if you change the value of module.dim
in your struct, the values returned by module.shape()
do not get updated. This is because the two function handle parameters gets set at the time of instantiation. You probably don't want this. Instead you can pass module.dim
and module.point
into your function handle as arguments:
module = struct('dim', [3 1 0.05], ...
'point', [0 0 0], ...
'shape', @(dim,point)cubeshape(dim,point))
module.shape(module.dim,module.point)
It's less graceful, but solves the problem, as the current values of module.dim
and module.point
will be used.
There are numerous other ways to solve your problem. The most standard is via object-oriented approaches. However, sometimes, that can be like swatting a fly with a sledgehammer (a very slow sledgehammer sometimes in Matlab's case). You may be able to do what you need with functions and some re-thinking of your problem.
来源:https://stackoverflow.com/questions/18110556/structure-field-is-function-matlab