Discussion:
initialize variable in a function
gigiolone123
2018-11-15 18:43:41 UTC
Permalink
now i give you a stupid example to understand my problem:

Main Program:

global cc;

cc=(1:2:300);

for i=1 to 50

ret=vv();

endfor



function vv

global cc;

cc(g)=g*2; ===> how can i initialize g = 1 ? (only the first time n)
g++;

endfunction


i want to inizialite the variable "g" with 1...
if can't initialize it in a function...i give initialize out it

there is another method? thank




--
Sent from: http://octave.1599824.n4.nabble.com/Octave-General-f1599825.html
Richardson, Anthony
2018-11-15 19:00:21 UTC
Permalink
Subject: initialize variable in a function
global cc;
cc=(1:2:300);
for i=1 to 50
ret=vv();
endfor
function vv
global cc;
cc(g)=g*2; ===> how can i initialize g = 1 ? (only the first time n)
g++;
endfunction
i want to inizialite the variable "g" with 1...
if can't initialize it in a function...i give initialize out it
there is another method? thank
Declare g to be persistent inside function vv(). It will be initialized to 1 and then retain its previous value between successive calls to vv(). Refer to section 7.2 of the manual for more details.

function vv
global cc;
persistent g = 1;
cc(g)=g*2;
g++;
endfunction

Tony Richardson

Loading...