Choose any workspace from dbstack for evalin

조회 수: 2 (최근 30일)
昊宣 徐
昊宣 徐 2024년 9월 30일
답변: Steven Lord 2024년 9월 30일
I wrote an App to add lines to axes. I need to pass some variables from the workspace where this App is called to the private handling function of this App.
function demoFcn()
fs = 20e3;
t = 1/fs:1/fs:1;
f = 100;
figure;
subplot(1, 2, 1);
plot(t, cos(2*pi*f*t));
% call drawLineApp to specify X and Y for extra lines in this axes
drawLineApp(gca);
end
For example, after finishing drawing some lines, I call this to draw in the existed subplot and I have two input text box in my App for x and y, where x=t and y=sin(2*pi*f*t). Both f and t are existed variables in the workspace of the drawing function (indeed, the drawing is not done in the base workspace). If I use:
methods (Access = private)
function drawButtonPushed(app, event) % button callback function
drawLineImpl(app);
end
function drawLineImpl(app)
% app.X is string "t" from the input text box
% app.Y is string "sin(2*pi*f*t)"
% app.target is the target axes to plot
% app.params is the plotting parameter cell array
X = evalin("caller", app.X);
Y = evalin("caller", app.Y);
plot(app.target, X, Y, app.params{:});
end
end
I would not get the desired result because 'caller' does not point to demoFcn().
So I want to track in the function stack where drawLineApp() is last called using dbstack. But evalin specifies workspace only with options 'base' and 'caller'. It comes to me whether I can specify any workspace found in the dbstack here.
By the way, I know that dbup can change the current workspace but only in debug mode. It does not work well in my case.
  댓글 수: 1
Stephen23
Stephen23 2024년 9월 30일
Just to clarify: so you want to write lots of very complex, inefficient, obfuscated code just to avoid simply passing data as arguments when calling a function? Well, if your goal is to make understanding, maintaining, and debugging your own code much harder for no obvious benefit, then there might be ways to do this. It will likely add bloat to your code.

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2024년 9월 30일
It comes to me whether I can specify any workspace found in the dbstack here.
No. For the evalin function in MATLAB you can specify 'base' or 'caller'. I second Stephen23's suggestion that you avoid using evalin at all and just pass the data using input and output arguments. Alternately you could pass the data between methods using properties of the object; set a property of the object in one of the object's methods and retrieve it in the other method(s) that get called.

추가 답변 (0개)

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by