Pass variable to .m file from app designer

23 次查看(过去 30 天)
I am new in matlab app designer, but I have gone through basics of it. I have a very simple query where I am stuck at.
I am calling "backtest.m" file in app designer
%backtest.m file
clc;
clear;
close all;
z = x + 6;
And this is the app designer code
methods (Access = private)
% Button pushed function: Button
function ButtonPushed(app, event)
x = app.xEditField.Value;
backtest;
end
end
I get an error where x is undefined. What should I do to remove this error?
Thanks in advance.
Prabhjeet
  3 个评论
prabhjeet singh
prabhjeet singh 2021-11-1
Thank you very much for the prompt response. I did exactly the same but now I am getting different error. Probably matlab does not like me.
Now the function file is (name of file is also backtest)
function backtest(x)
z = x + 6;
end
And code in app designer is as follows
% Callbacks that handle component events
methods (Access = private)
% Button pushed function: Button
function ButtonPushed(app, event)
%global xx;
x = app.xEditField.Value;
backtest(x);
app.zEditField.value = z;
end
end
z should show the final value from backtest.m file in app design view.
Sorry for troubling again.
Thanks,
Prabhjeet

请先登录,再进行评论。

采纳的回答

Yongjian Feng
Yongjian Feng 2021-11-1
编辑:Yongjian Feng 2021-11-1
Return z value from your funciton backtest.m:
function z = backtest(x)
z = x + 6;
end
Call this function from app designer like this:
z = backtest(x);
Basically you shall pass input/output to/from your function using input argument and return. Don't pass data using global variables.
  6 个评论
prabhjeet singh
prabhjeet singh 2021-11-2
Thank you for the prompt response. Unfortunately, it did not work again. However, I found the solution by defining variables in public property. Now it is working the way it should.
Thank you once again for your responses.
Thanks,
Prabhjeet
Ayman Shaban
Ayman Shaban 2022-3-18
Thank you very much for your answer, i have another Q , how can i show the result of .m file on app designer after already calling the .m file

请先登录,再进行评论。

更多回答(1 个)

Cris LaPierre
Cris LaPierre 2021-11-1
This will never work as written. The clear inside the m-file, whether a script or function, will remove any variables, including the one passed in.
Remove the following from your m-file
clc;
clear;
close all;
Place the m-file in the same folder as your app. Now when you call it, it's the same as adding the code from your m-file to the code in the callback function.
Note that the variable z will only exist inside the callback function. You need to keep in mind your variable scope.
I do agree that turning this into a function makes more programatic sense to me, but it is not necessary to get it to work.

类别

Help CenterFile Exchange 中查找有关 Develop Apps Using App Designer 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by