Borrar filtros
Borrar filtros

How can I pass a function name into another function?

2 visualizaciones (últimos 30 días)
Peter Fokker
Peter Fokker el 30 de Mzo. de 2023
Movida: Torsten el 30 de Mzo. de 2023
I try to make something flexible that gives a function name as a variable name.
Tried the following:
file named tt.m
function tt
x = 0:10;
y1 = testfun(@line,x);
y2 = testfun(@quad,x);
end
file named testfun.m:
function b = testfun(fun, x)
b = fun(x);
function y = line(x)
y = x;
end
function y = quad(x)
y = x.^2;
end
end
How to get it working?
Any help appreciated!

Respuesta aceptada

Stephen23
Stephen23 el 30 de Mzo. de 2023
Editada: Stephen23 el 30 de Mzo. de 2023
The functions that you nested inside TESFUN are only visible within TESTFUN:
You could either write them as functions in their own files or write them as normal local functions:
x = 0:10;
y1 = testfun(@line,x)
y1 = 1×11
0 1 2 3 4 5 6 7 8 9 10
y2 = testfun(@quad,x)
y2 = 1×11
0 1 4 9 16 25 36 49 64 81 100
function b = testfun(fun, x)
b = fun(x);
end
function y = line(x)
y = x;
end
function y = quad(x)
y = x.^2;
end

Más respuestas (1)

Torsten
Torsten el 30 de Mzo. de 2023
Movida: Torsten el 30 de Mzo. de 2023
"fun" is an external input argument to "testfun". Thus "fun" can not be used as a nested function in "testfun".
Using "line" and "quad" as independent external functions that are not nested within "testfun" will work.
Or use
tt
y1 = 1×11
0 1 2 3 4 5 6 7 8 9 10
y2 = 1×11
0 1 4 9 16 25 36 49 64 81 100
function tt
x = 0:10;
y1 = testfun(@line,x)
y2 = testfun(@quad,x)
function b = testfun(fun, x)
b = fun(x);
end
function y = line(x)
y = x;
end
function y = quad(x)
y = x.^2;
end
end

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by