Reputation: 1
If I have a function f(x,y), I want to know how to define another function (say g) where g(x) = f(x,y), where y has been defined beforehand, either explicitly or as the input of another function.
I know this is probably quite simple but my code does not seem to work and I cannot find a solution in the documentation.
Upvotes: 0
Views: 271
Reputation: 114440
You are probably looking for anonymous functions.
A very common use-case is minimiziation. You often need to minimize a function of multiple variables along a single parameter. This leaves you without the option of just passing in constants for the remaining parameters.
An anonymous definition of g
would look like this:
g = @(x) f(x, y)
y
would have to be a variable defined in the current workspace. The value of y
is bound permanently to the function. Whether you do clear y
or assign a different value to it, the value of y
used in g
will be whatever it was when you first created the function handle.
As another, now deleted, answer mentioned, you could use the much uglier approach of using global
variables.
The disadvantages are that your code will be hard to read and maintain. The value of the variable can change in many places. Finally, there are simply better ways of doing it available in modern versions of MATLAB like nested functions, even if anonymous functions don't work for you for some reason.
The advantages are that you can make g
a simple stand alone function. Unlike the anonymous version, you will get different results if you change the value of y
in the base workspace, just be careful not to clear it.
The main thing to remember with globals is that each function/workspace wishing to share the value must declare the name global (before assigning to it to avoid a warning).
In the base workspace:
global y
y = ...
In g.m
:
function [z] = g(x)
global y;
z = f(x, y);
I am not particularly recommending this technique, but it helps to be aware of it in case you can't express g
as a single statement.
A note about warnings. Both anonymous functions and globals will warn you about assigning to a variable that already exists. That is why putting a global
declaration as the first line of a function is generally good practice.
Upvotes: 1
Reputation: 933
f = @(a,b) a^2 + b^2;
y = 4;
g = @(x) f(x,y);
g(2)
ans = 20
Upvotes: 1