how to use function handles
Show older comments
Instead of the following, I want to use function handles and move if-statments out of the loop:
for n=1:10
if a==0
A = function2(n,a,b);
else
A = function1(n,a,b,c,d);
end
end
function A = function1(n,a,b,c,d)
A = n+a+b+c+d; % here it can be any expression
end
function A = function2(n,a,b)
A = n*a*b; % here it can be any expression
end
moving if-statement outside of the loop and using handles:
if a==0
func = @function2;
else
func = @function1;
end
and then I can solve my problem in two ways as
for n=1:10
A = func(n,a,b,c,d);
end
function A = function1(n,a,b,c,d)
A = n+a+b+c+d;
end
function A = function2(n,a,b,~,~)
A = n*a*b;
end
or as
for n=1:10
A = func(n,a,b,c,d)
end
function A = function1(n,a,varargin)
b = varargin{1};
c = varargin{2};
d = varargin{3};
A = n+a+b+c+d;
end
function A = function2(n,a,varargin)
b = varargin{1};
A = n*a*b;
end
Is there any more elegant way to do this?
1 Comment
G A
on 29 Aug 2021
Accepted Answer
More Answers (1)
I think the basic idea you need is
f1 = @(x) x;
f2 = @(x) x.^2;
f = @(a,x) (a~=0)*f1(x) + (a==0)*f2(x);
f(0,2)
f(1,2)
4 Comments
Hm. Not finding a good way to handle this that does not potentially result in empty, Inf, or NaN when one of the functions does not have all the arguments. For example, you could pass zeros into the function when they are not needed, but it is potentially hazardous:
f1 = @(x) x;
f2 = @(x,y) x.^2 + y.^2;
f = @(a,x,y) (a~=0)*f1(x) + (a==0)*f2(x,y);
f(0,2,3)
f(1,2,0)
the cyclist
on 29 Aug 2021
Searching keywords such as conditional anonymous function MATLAB turns up a lot of these same ideas. I did not find a great solution.
Categories
Find more on Entering Commands in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!