[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to share variables between functions
From: |
Guillem Borrell Nogueras |
Subject: |
Re: How to share variables between functions |
Date: |
Tue, 3 Apr 2007 16:14:46 +0200 |
User-agent: |
KMail/1.9.5 |
Most of times the code becomes simpler using anonymous functions via function
handles like `y=@(x,t) ...`. This is a very useful trick in Matlab where
every function means yet another .m file. The anonymous functions have the
interesting property of catching all the variables in their space:
. >>a=2;
. >>f = @(x) x*a;
. >>f(3)
ans = 6
is legal and keeps the variable "a" in the main workspace. Try to rewrite
your code using this trick and maybe there will be no need of using any
global variable. This is the recommended way in matlab's documentation.
NOTE: the anonymous functions work this way in octave 2.9. Octave 2.1 will
complain saying that the variable "a" is unknown.
On Tuesday 03 April 2007 07:38, Evan wrote:
> 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?
>
> Thanks in advance
> _______________________________________________
> Help-octave mailing list
> address@hidden
> https://www.cae.wisc.edu/mailman/listinfo/help-octave