Why do I get an "Error using sort" message when calling the "intersect" method on two enumeration arrays in MATLAB R2023a?

I create an Enumeration class called DayOfWeek. Here is the code for the DayOfWeek class.
classdef DayOfWeek properties isWeekday logical end % CONSTRUCTOR METHOD methods function EnumObj = DayOfWeek(isWeekdayValue) EnumObj.isWeekday = isWeekdayValue; end end enumeration Monday (true), Tuesday (true), Wednesday (true), Thursday (true), Friday (true), Saturday (false), Sunday (false) end end
I then create two enumeration arrays in the MATLAB Command Window.
>> onsiteDays = [DayOfWeek.Tuesday DayOfWeek.Thursday]; >> weekdays = [DayOfWeek.Monday DayOfWeek.Tuesday DayOfWeek.Wednesday DayOfWeek.Thursday DayOfWeek.Friday];
The two arrays are created successfully, but why am I getting the following error message when I call the "intersect" method on them? Is this a bug in MATLAB?
>> intersect(onsiteDays, weekdays) Error using sort Incorrect number or types of inputs or outputs for function 'sort'. Error in unique>uniqueR2012a (line 208) sortA = sort(a); Error in unique (line 103) [varargout{1:nlhs}] = uniqueR2012a(varargin{:},true,true,false); Error in intersect>intersectR2012a (line 226) c = unique(b(ismember(b,a))); Error in intersect (line 111) [varargout{1:nlhs}] = intersectR2012a(varargin{:});

 Accepted Answer

This observed behavior in MATLAB is expected. The DayOfWeek class includes properties, making it a non-pure enumeration. Currently, we do not support sorting in non-pure enumerations due to the ambiguity surrounding how to sort these enums - whether based on the properties or the enumerations themselves.
Although the behavior is expected in MATLAB, it is an enhancement that could be made. Our development team is aware of it and will consider it for future releases.
One possible workaround is to override the "sort" method in the enumeration class. Here is an example that demonstrates sorting the enums by their names:
methods
function [sortedEnums, idx] = sort(enums)
names = string(enums);
[~,idx] = sort(names);
sortedEnums = enums(idx);
end
end

More Answers (0)

Categories

Products

Release

R2023a

Community Treasure Hunt

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

Start Hunting!