2

When I pass a function (let's call it f) into my Base function , the Base function doesn't recognize the f function , without using '' quotes , here's the code :

function y = test(a, b, n ,f)

if ( rem(n,2) ~= 0 )
   error ( 'n is not even' )
end

% create a vector of n+1 linearly spaced numbers from a to b
x = linspace ( a, b, n+1 );

for i = 1:n+1
    % store each result at index "i" in X vector
    X(i) = feval ( f, x(i) );
end
y=sum(X);
end

And this is f.m :

function [y] = f (x)
y = 6-6*x^5;

When I run from command line with quotes :

>> [y] = test(0,1,10,'f')

y =

   52.7505

but when I remove them :

>> [y] = test(0,1,10,f)
Error using f (line 2)
Not enough input arguments.

Where is my mistake ? why can't I execute [y] = test(0,1,10,f) ?

Thanks

Ben A.
  • 1,039
  • 6
  • 13
JAN
  • 21,236
  • 66
  • 181
  • 318

2 Answers2

3

The function feval expects either the function name (i.e., a string) or a function handle as input. In your code, f is neither a name, nor a handle. Use either the string 'f' or the handle @f when calling your base function test.

If, as posted in the comments, function handles are not allowed per assignment in the call to the base function, you can still use the function handle to create a string with the name of the function. This functionality is provided by the function func2str:

functionName = func2str(@f); 

test(0,1,10,functionname);
H.Muster
  • 9,297
  • 1
  • 35
  • 46
  • I can't pass `@f` (assignment rules) , I need to pass only `f` , any other suggestion maybe ? – JAN Jun 22 '12 at 10:50
  • 1
    What do you mean by 'assignment rules'? Passing `@f` is the correct thing to do here. In other words, `test.m` is fine, you need to invoke it as `test(0,1,10,@f)`. – Edric Jun 22 '12 at 11:21
  • @ron Are function handles prohibited in general or just in the call to `text()`? – H.Muster Jun 22 '12 at 11:23
  • @H.Muster: Just in the call of `test(...)` . Please note that I can always do this : `q = @(x) 6*x^2 +1` and then execute `test()` like this : `test(0,1,10,q)` with no `@` ... but when I have `q` as an `m-file` , this won't work ... see what I mean ? – JAN Jun 22 '12 at 11:26
2

Try passing @f as the argument instead of 'f', and also change the line to

X(i) = f(x(i));

The thing is that just f is not a function handle. Also there's no need to use feval in this case.

Ansari
  • 8,168
  • 2
  • 23
  • 34
  • I can't pass `@f` (assignment rules) , I need to pass only `f` , any other suggestion maybe ? thanks – JAN Jun 22 '12 at 10:09