Scripts, I/O, Functions

Back arrow to return.

Demos 1: Local Variables

%incx.m

% I don't like this demo any more... needs substantial work! CB 9/15
function incx % a trick to save writing 3 fn files

x = 10
incx1
incx1()
incx2  % oops, needs an argument, so comment out
incx2(5)
y = 10
incx2(y)
y
pause;
disp('*************');
x = 100
incx2(x)
x
pause
disp('*************');
z = -99;
incx3(z)
x
z
newlocal  % oops, not defined in this scope!
pause;
end


function   incx1
% increment x
x = x+1   % gives error, so comment out
end

function   incx2(x)  % not same x!
 % increment x
disp('into inc2');
x = x+1
disp('returning from inc2');
end

function   incx3(x)
z = 55;
newlocal = pi;
% increment x
disp('into inc2');
x = x+1
z
newlocal
disp('returning from inc2');
end

%end incx.m

Demos 2: Nested Functions and Recursion

%demo2.m
function demo2
% more scoping fun
x = 100
x = func_one(x)  % reassigns x
facile(5)
end


function x = func_one(x)   % two different x's
x = func_two(x) + func_two(x);
end

function y = func_two(z)
y = z^2;
end


function xfact = facile(x)  % factorial 5! = 5*4*3*2*1 = 5*4!
if x <= 1
  xfact = 1
else
  xfact = x*facile(x-1)
end
end

%end demo2.m

Back arrow to return.

Demos 3: Globals and Persistents

This demo is set up in an advanced way using subfunctions (Attaway 5.2.2). The idea is to put more than one function in a file. The M-file has the name of the first (primary) function. That function is the one you can call from outside. You define other (sub) functions below it. They are LOCAL! The primary function can use them but nothing else can. It's a structuring tool to reduce confusion. If a function is useful ONLY to one parent or primary function, sub-functions are a good idea. Here it's just for efficiency.

grab the whole thing, paste it into the editor, and save it... it should then appear (remember ls command) in the directory as demo3. Then if you type
>>demo3;
It will run like a script.

Next, notice at top level that MYGLOB isn't in the workspace. It was never defined there. If you type to the commands
>> global MYGLOB;
>> demo3;
>> MYGLOB
you see that calling the demo3 function has assigned a value to MYGLOB.

%--------copy following down to end copy --------
function demo3
%global and persistant
global MYGLOB;

MYGLOB = 0;
MYGLOB
glob_func()
MYGLOB
pause
kount = -99
fprintf('top level, kount = %d \n',kount);

countfunc();
countfunc();
countfunc();
fprintf('top level, kount = %d \n',kount);
end  % demo3

function glob_func()
global MYGLOB;
disp('enter glob_func');
MYGLOB
MYGLOB = -99
disp('exit glob_func');
end

function countfunc()
persistent kount;
disp('into countfunc');
if isempty(kount)
    kount = 0
else
    kount = kount+1
end
fprintf('weve kounted %d times.\n',kount);
disp('out of countfunc');
end

%------------end copy ----------- 

Back arrow to return.

---

Last update: 04/22/2011: RN