Why can I not pass a maths function into another function
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Campbell Gray
el 30 de En. de 2018
Comentada: Walter Roberson
el 30 de En. de 2018
I have a function 'heun' which I am trying to pass a mathematical function into, I have managed to do this before but can not do it consistently.
fb = @(t,y)(5*y(t));
y = heun( fb, 0.1/10, 10, 0, 1 );
this is my error message:
Function 'subsindex' is not defined for values of class 'function_handle'
Please help
5 comentarios
Adam
el 30 de En. de 2018
Editada: Adam
el 30 de En. de 2018
This is fundamentally different code to what you showed in the question. You are trying to use heun as both the function name and the name of the variable to which you are trying to assign the result. This clearly won't work. Use different names for variables and for functions!!
Walter Roberson
el 30 de En. de 2018
The above would work the first time, because the first time through the variable heun has not been assigned to so heun refers to the function. The second time through, though, heun is now a scalar value rather than a reference to the function.
Respuesta aceptada
Walter Roberson
el 30 de En. de 2018
At that point in your code, heun is a variable (other than a function handle) rather than a function.
2 comentarios
Walter Roberson
el 30 de En. de 2018
The error says that you tried to use a function handle as a subscript. That would happen if you tried to do something like this:
heun = 17;
fb = @(t,y)(5*y(t));
y = heun( fb, 0.1/10, 10, 0, 1 );
In this code, when the third line is executed, heun refers to the array named heun, rather than to the available function named heun, so this would be a request to subscript the array named heun with first index fb (a function handle), second index 0.01, third index 10, fourth index 0, fifth index 1.
The priority for resolving names always goes to local variables first. Otherwise code such as
sum = 0;
for K = 1 : 5
sum(K+1) = sum(K) + K;
end
would not be able to work, if MATLAB gave priority to function calls over local variables.
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!