user2241980
user2241980

Reputation:

How to pass function as an argument?

Im completely new to matlab and I cant seem to find any info about this. How may I implement this?

function [R] = GetY(func,x)
R = func(x);
end;

example: getY(5x+2, 1)
R = 5(1)+2 = 7

Upvotes: 0

Views: 64

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Use a function_handle:

function R = GetY(func,x)
    R = func(x);
end

...

>> GetY(@sin, pi/2)
ans = 
    1
>>
>> GetY(@(x) x.^2 + 4, 2)
ans = 
    8

Upvotes: 3

Related Questions