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