"See" variable inside a function before it returns?
5 次查看(过去 30 天)
显示 更早的评论
I have a script which calls a function that can take 15+ minutes to return with an output. During that time, I'd like to be able to "see" into the function in order to see where it's at. Is there a way to expose a variable which the script (or function) calling a function can see at all times? For example, in the code below, I'd like to have the script which calls junkfun(x) be able to "see" i and perform calculations with on it to fprintf an ETA for the function to complete.
function [p i] = junkfun(x)
load('data.mat')
i = 1;
sum_one = 0;
for i = 1:x
pause(1)
sum_one = sum_one+sum(gridrate.p_a(1:100));
end
p = table(sum_one);
end
0 个评论
回答(2 个)
Steven Lord
2018-1-11
First, a suggestion: don't load your data inside the function. Call load outside the function and pass the struct returned by load into the function as an additional input. That will avoid accessing the disk every time your function is called. If you're calling your function in a loop, that work could take the majority of the time required by your function.
If you're using release R2016a or later and you want to interactively check the status of the function, you can use the pause button in the MATLAB Editor.
If you must make one of junkfun's variables available to its caller, one way to do so would be to make junkfun a nested function inside its caller.
3 个评论
Steven Lord
2018-1-11
There is a way to do what you ask. However the general recommendation is "Use global variables sparingly, if at all."
As stated on that documentation page, by making a variable in your function global you're giving any piece of code with access to the global workspace permission to influence how that function operates by changing that global variable. Debugging issues caused by a change in global state to identify the cause of the change can be challenging to say the least.
One other alternative that comes to mind, if this is part of a GUI or some object-oriented system involving a handle class the GUI or class could provide a method junkfun could call to update the GUI's data or a property of the handle object. The GUI or handle object could query its data and/or properties and report the status that way.
Fangjun Jiang
2018-1-11
May I suggest waitbar(), adding inside your function? For example
h = waitbar(0,'Please wait...');
for i=1:1000,
% computation here %
waitbar(i/1000,h)
end
close(h)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!