How to Use sort to Sort an Array of Custom Class Objects in MATLAB?
14 次查看(过去 30 天)
显示 更早的评论
I have already overloaded the eq, lt, and gt methods in my class definition, but I am still encountering an issue when trying to sort using the sort function.
error sort
Incorrect number or types of inputs or outputs for function sort.
3 个评论
回答(1 个)
Divyam
2024-7-16
编辑:Divyam
2024-7-16
Hi Jia, ensure that your custom class is defined in a ".m" file with name as the class name. "MyClass.m" has been attached as the reference class for the code below.
To test sorting, the following code was created in a different MATLAB file in the same directory where the class was defined.
% Creating an array of custom class objects
array = [MyClass(5), MyClass(2), MyClass(8), MyClass(3)];
% Extracting the "Value" of the objects in an array using the arrayfun method
valuesExtract = arrayfun(@(obj) obj.Value, array);
% Sorting the values to get the sorted indices
[~, sortedIndices] = sort(valuesExtract);
% Reorder the array based on the sorted indices
sortedArray = array(sortedIndices);
% Displaying the sorted values
for i = 1:length(sortedArray)
fprintf("%d ", sortedArray(i).Value);
end
The issue might be caused by not using "arrayfun" to extract the "Value" property which has to be compared and comparing the property directly.
For more information regarding the use of "arrayfun" method refer to the following documentation: https://www.mathworks.com/help/matlab/ref/arrayfun.html
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!