Share one callback with multiple elements and pass on the respectively number in the callback

2 次查看(过去 30 天)
Hi everyone,
is there a way to refer multiple elements with systematical names (e.g. Dropdown_Ydata1, Dropdown_Ydata2, Dropdown_Ydata3) with a identical function to one callback, then read the number (1,2 or 3) and pass on this number to the following code?
%for example:
%shared variables through the app : y1, y2, y3
% ValueChanged function: Dropwdown_Ydata1, Dropwdown_Ydata2, Dropwdown_Ydata3
%% read number (1 ... 3) and save it as "i" (I had the idea to read the tag of the
% respectively App and then get the number with regexp)
source = event.Source.Tag;
i = regexp(source,'\d+','match')
x = ... % doesn't matter
%% write the number (i) in the following code
% im not sure how to do this because i read that dynamically changing variables are "wrong".
% Maybe store them in a string/matrix - i dont know
y = app.y(i).(app.Dropwdown_Ydata(i).Value);
plot(app.UIAxes, x, y);
This would save me a ton of code because i have multiple elements(40 to 50) with the exact same callback. The only part that is changing is the name of the element (e.g. app.name(x)). I started working with matlab just a few weeks ago so please forgive me some obviously mistakes.
edit 15.06.21:
i found a way to do it, maybe one of u can tell me if this is a good idea or just mixing "wrong" things. Im open to a better/faster way.
%shared variables through the app : y1, y2, y3
% ValueChanged function: Dropwdown_Ydata1, Dropwdown_Ydata2, Dropwdown_Ydata3
source = event.Source.Tag; %get the Tag of the source
i = regexp(source,'\d+','match'); %get the number out of the tag (outputs a cell array)
i = str2double(i); %outputs a number
y = app.(sprintf('y%d', i)).(app.(sprintf('Dropwdown_Ydata%d',i)).Value); %sets the name of the apps (e.g. app.y1.(app.Dropwdown_Ydata1.Value));
plot(app.UIAxes, y);
the sprintf-thing makes the code a little bit messy but as mentioned it saves me a ton of code.

采纳的回答

Mohammad Sami
Mohammad Sami 2021-6-15
Yes you can assign the same callback to multiple objects. The above code you shared is fine.
However you can access the value of the dropdown directly since its passed in to you inside the event object.
Also if you make the variable y as an array of struct you will not need to use sprintf.
source = event.Source.Tag; %get the Tag of the source
i = regexp(source,'\d+','match'); %get the number out of the tag (outputs a cell array)
i = str2double(i); %outputs a number
y = app.y(i).(event.Value); %sets the name of the apps (e.g. app.y(1).(app.Dropwdown_Ydata1.Value));
plot(app.UIAxes, y);

更多回答(0 个)

类别

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

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by