help-octave
[Top][All Lists]

## Re: another question : arrays of functions ???

 From: Ted Harding Subject: Re: another question : arrays of functions ??? Date: Thu, 13 Jun 1996 20:19:11 +0100 (GMT+0100)

```( Re Message From: Kay Hamacher )
>
> Status:
>
> Hello.
>
> There is another question which comes up by thinking
> of a solution for an exercise :
>
> Is there a way to declare arrays of functions ?
>
> I think of the possibilities of Pascal :
> Var a : Array[1..20] Of Function(x:Real) : Real;
>
> and then do callings like
> for i := 1 to 20 Do   b := b + a[i](3);
>
> Kay

Octave does not provide for the declaration of arrays of functions in the
way Pascal (or C) does. You can, however, emulate it by constructing an
array of function names and using the "eval" function. But you need to
make sure that you "fudge" the function names to be all the same length in
the array. The function definitions would be given separately, and
individually, as in P or C.

For example:

function y = cos_2(x)
t = cos(x); y = t.*t;
endfunction

function y = cos_3(x)
t = cos(x); y = t.*t.*t;
endfunction

fn = ["  cos"; "cos_2"; "cos_3"];

x = [ 0.25 0.5 0.75 ];
y = [];
for i = 1: 3, t = eval ([ setstr( fn(i,:) ) "(x);" ]); y=[y;t] endfor

Best wishes,