"See" variable inside a function before it returns?
조회 수: 1 (최근 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.
Stephen23
2018년 1월 12일
+1 well spotted to move load outside the loop, and suggesting nested functions.
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에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!