Populate drop down menus with enums
Show older comments
Hello all,
I trying to understand enumerations and how they are to be used in matlab. I have 2 questions:
1.: In C# I can just define enums in a class:
enum someSpecificValues { one = 1, two = 2, three = 3 }:
And later use them
var enumTest = someSpeficValues.one;
Now, what I understood from the MATLAB help is that I need to define each enum as a class and then call that from within my class. I am developing a driver library, where I need a couple of settings as enums. Do I really need to define them in that way or is there a way to define them within the class? Creating them inside the class has the added advantage that they're confined to the class, where they make sense.
2.: Along with my driver I'd like to create some examples in the app creator, where I want to display these enumerated values as drop down menus, so people don't just enter random values. Is there a way to link the drop down to the enumeration or would I have to write the values by hand and hope not to make an error? Again, in C# you could bind the drop down to the enum (technically, you'd bind to the list, but the effect is the same) and changes to the enum would be reflected on your UI.
I have tried to use the DropDown.Items property and realized this accepts string arrays and not enumerations. I don't know how to correctly convert my enumeration, though. Suppose I have the class:
classdef readModes
enumeration
ZIF, SH, SHN, HDR, DD
end
end
Then the following would not work.
app.DropDown.Items = enumeration(readModes.ZIF);
But what does?
1 Comment
Peter Foerster
on 28 Nov 2018
Answers (3)
Peter Foerster
on 28 Nov 2018
Karl Erik Thoresen
on 13 Jan 2022
Try:
app.DropDown.Items = cellstr(enumeration(myClass.SomeEnum));
classdef MyClassDef
enumeration
Item1
Item2
Item3
end
methods(Static)
% create an array of enumeration item name strings
function il = itemlist()
items = ?MyClassDef;
Ni = length(items.EnumerationMemberList);
il = strings(Ni,1);
for i = 1:Ni
il(i) = items.EnumerationMemberList(i).Name;
end
end
end
end
Use the itemlist to populate the dropdown. This can be done through adding a callback - just add the following to the callback:
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
myitems = MyClassDef.itemlist;
app.MyItemsDropDown.Items = myitems;
end
end
Where MyItemsDropDown is the name you gave to the dropdown that you created in the app designer.
Categories
Find more on Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!