[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
## RE: How to share variables between functions

**From**: |
Hall, Benjamin |

**Subject**: |
RE: How to share variables between functions |

**Date**: |
Tue, 3 Apr 2007 11:38:07 -0400 |

>* | In some cases, it seems that sharing variables between functions*
>* | cannot be avoidable. for example*
>* | *
>* | function y=f(x)*
>* | global x;*
>* | y=quad(subf,0,1);*
>* | clear x;*
>* | endfunction*
>* | *
>* | function f=subf(t)*
>* | global x;*
>* | f=g(x,t);*
>* | endfunction*
>* | *
>* | function y=g(x,t)*
>* | ......*
>* | endfunction*
>* | *
>* | because "quad" function only accept functions with one scalar*
>* | argument, other arguments have to be passed by other means. The only*
>* | way I know is to use global variables as the above example *
>* does. But I*
>* | don't think it is a good idea for that the variable "x" *
>* would also be*
>* | accessible elsewhere, thus confusion may be caused. Is there any*
>* | method to share local variables between functions, that is, these*
>* | variables are not visible elsewhere?*
>* *
>* With Octave 2.9.10, you can write*
>* *
>* function y = f (x)*
>* y = quad (@(t) g (x, t), 0, 1);*
>* endfunction*
>* function y = g (x, t)*
>* y = t*x;*
>* endfunction*
>* *
I've also used persistent variables...
function y = f(x, otherparam )
persistent param = [];
if ( nargin > 1 )
param = otherparam;
return
end
y = param*x;
endfunction
then do an "initialization" call first
f(0,0.33);
quad( @f, 0, 1 )