0

let's say we have function like below:

function Output=DoSomething(f)
...
...
end

where 'f' is a function that user inputs , like 'sin(t)' , 'x^2' or a vector of functions. the function DoSomething gets f and perform some operation on it. for example, evaluates 'f' at t=pi/2,pi,2*pi,... and put result in Output vector. how can this be done in MATLAB? should f be an string variable? if yes, does it need to convert to another data type? i'm getting errors doing this.

2 Answers 2

2

A couple of example ways to do this

  1. Make the input f a function handle

    function [output] = dosomething(f, varargin) 
    output = f(varargin{:});  
    end
    
    >>f = @(x, y) sqrt(x.^2 + y.^2);
    >>dosomething(f, [3 5 8], [4 12 15])
    >>ans =
    >>5    13    17
    
  2. Make f a string, and use 'eval' (first is better practice, I think, this second one fails if nargin is less than 2, but not if nargin is >=3 even though the function doesn't use them.)

    function [output] = dosomething(f, varargin) 
    output = eval(f);  
    end
    
    >>f = 'sqrt(varargin{1}.^2 + varargin{2}.^2)';
    >>dosomething(f, [3 5 8], [4 12 15])
    >>ans =
    >>5    13    17
    
  3. If you want to be able to input multiple functions, you can do something like

    function [output] = dosomething(f, varargin) 
    output = cellfun(@(x) x(varargin{:}), f, 'UniformOutput', false);  
    end
    >> f{1} = @(x, y) sqrt(x.^2 + y.^2);
    >> f{2} = @(x, y) atan2(x, y);
    >> A = dosomething(f, [3 5 8], [4 12 15]);
    >> A{1}
    ans =
    5    13    17
    >> A{2}
    ans =
    0.6435    0.3948    0.4900
    
Sign up to request clarification or add additional context in comments.

Comments

0

Wasn't sure whether to make this a comment or an answer...

It's really difficult to do this as there are all sorts of different ways of inputting functions into Matlab. I think that the easiest thing to do would be to make f an anonymous function, e.g.

f=@(x,y) x.^2+y.^2;

then inside the DoSomething function you can do f(1,2) or f(1:10,11:20).

Note if the function is not defined using element-by-element operation (.*, etc.) then you can convert it so that it can take vector arguments by doing

syms q w
f=matlabFunction(f(q,w),'vars',[q w]);

which could prove useful.

Even if you don't make f an anonymous function for the input into DoSomething, converting whatever you get into either an anonymous function or a vector of values of f is probably a good idea in terms of performance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.