How can I retrieve variables from a nested function and use them on the parent function?
3 次查看(过去 30 天)
显示 更早的评论
Hey guys, I have a little problem here with variables on nested functions. Here is the code:
function Parent
%code goes here
function dx = odestribeck (t,x)
dx=[x(2);-(Fc*tanh(x(2))+sig2*x(2)+(Fs-Fc)*exp(-(x(2)/Vstri)^2)+k*x(1))/m];
ode = @odestribeck;
alg;
function alg
[t,x]=ode15s(ode,[0,5],[0,5]);
end
end
%Command to plot variables t and x defined on function alg goes here.
end
As written on the code, I want to include a plot command on the parent function to the variables t and x defined on alg function (second level nested function).
Thank you in advance!
0 个评论
采纳的回答
David Young
2015-2-1
编辑:David Young
2015-2-1
Edit: The answer below addressed the question of how to get results from nested functions, but doesn't adequately take into account the need to provide the correct function handle argument to ode15s. See the comments. Anyone more expert in using the ode solvers: please contribute!
One method is to return t and x from odestribeck in the normal way:
function Parent
...
[t,x,dx] = odestribeck(...);
plot(t,x);
...
function [t, x, dx] = odestribeck (t,x)
...
alg;
function alg
[t,x]=ode15s(ode,[0,5],[0,5]);
end
end
end
Note that the call to plot can go after the nested function definition if you like, but it's probably clearer to leave it with the other code in Parent, before the nested definitions - it doesn't affect the order of execution.
Alternatively, you can make t and x global to both the nested functions, by initialising them in Parent and not passing them as arguments:
function Parent
...
t = ...;
x = ...;
dx = odestribeck;
plot(t,x);
...
function dx = odestribeck
...
alg;
function alg
[t,x]=ode15s(ode,[0,5],[0,5]);
end
end
end
Again, you can put code after the nested function definitions if you wish.
3 个评论
David Young
2015-2-1
Sorry - I hadn't noticed when I wrote my answer that odestribeck is the function argument to the solver. I was focused on the idea that the core problem was getting information to and from nested functions, but it's not so simple.
I think your second comment is in the right direction - that is, you should simplify the structure - my suggestion would be
function Parent
...
[t,x]=ode15s(odestribeck,[0,5],[0,5]);
plot(t, ...);
function dx = odestribeck (t,x)
dx=[x(2);-(Fc*tanh(x(2))+sig2*x(2)+ ...
(Fs-Fc)*exp(-(x(2)/Vstri)^2)+k*x(1))/m];
end
end
If this is still unsuccessful, I am not sure what the problem is. It may be worth posting another question, but focusing on the ode solver rather than on the nested function structure, to get a more expert reply.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!