[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
## functions within functions?

**From**: |
Ferdinand Schinagl |

**Subject**: |
functions within functions? |

**Date**: |
Thu, 01 Oct 1998 12:14:28 +0100 |

Hi,
obviously it is not possible to define
functions within functions directly, like:
function a(x)
function y = b(x)
y = sin(x)
end
end
However, as I found out, it can be done by
evaluating strings (at runtime then, of course):
function a(x)
str = sprintf("function y = b(x); y = %e*sin(x); end;",x)
eval(str);
end
or by means of writing into an external file
which then contains all the necessary information:
function a(x)
handle = fopen("b.m","w");
fprintf(handle,"function y = b(x)\n y = %e*sin(x);\nend",x);
fclose(handle);
end
Well, both solution do not work when a is called
from another function, at least to a certain extent:
First, when defining b by 'eval':
function c(x)
for i=1:3
# clear b;
a(i);
b(x)
end
end
fails as long as I don't clear b (remove the comment and
you'll see what happens).
Second, b defined via file (by 'fprintf') takes some time
until b is recognized the way it is defined. Just type
octave:70> a(1);b(1)
ans = 0.84147
octave:71> a(2);b(1)
ans = 0.84147
octave:72> a(2);b(1)
ans = 1.6829
The only difference between :71> and :72> is the amount
of time that's gone. If you wait for a secon or so,
you get :72>, if you invoke a(2);b(1) immediately after
a(1);b(1) one gets :71>!
You can (perhaps only) avoid this using:
a(1);source("b.m");disp(b(1));a(2);source("b.m");disp(b(1))
Are there any concerns?
Best regards,
Ferdinand.

**functions within functions?**,
*Ferdinand Schinagl* **<=**